2016年10月7日金曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原著: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の第1章(手続きによる抽象の構築)、1.3(高階手続きによる抽象)、1.3.4(値として返される手続き)、問題1.45.を取り組んでみる。

その他参考書籍

問題1.45.

コード(Emacs)

(begin
  (load "procedures.scm")
  (newline)
  (define (p x) (display x) (newline))
  
  (define tolerance 0.00001)
  (define (fixed-point f first-guess)
    (define (close-enough? v1 v2)
      (< (abs (- v1 v2)) tolerance))
    (define (try guess)
      ((lambda (next)
         (if (close-enough? guess next)
             next
             (try next)))
       (f guess)))
    (try first-guess))

  (define (average a b) (/ (+ a b) 2))
  (define (average-damp f)
    (lambda (x) (average x (f x))))

  (define (compose f g)
    (lambda (x) (f (g x))))

  (define (repeated proc n)
    (if (= n 1)
        (lambda (x) (proc x))
        (compose proc (repeated proc (- n 1)))))

  (define (n-root n x)
    (fixed-point ((repeated average-damp n)
                  (lambda (y) (/ x (expt y (- n 1)))))
                 1.0))
  (for-each (lambda (n)
              (p (n-root n 2)))
            '(1 2 3 4 5 6 7 8 9 10))
  'done)

入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))

$ ksi < sample45.scm
ksi> 
1.999992370605469
1.414204706074303
1.259906125654789
1.189182878162889
1.148646239546608
1.122369731252727
1.103920749306572
1.090201766882419
1.079505929576538
1.070765417157089
=> done
ksi> $

0 コメント:

コメントを投稿