Keep on moving

あんまりまとまってないことを書きますよ

第一章(2)

例題1.1.7
(define (average x y)
  (exact->inexact (/ (+ x y) 2)))

(define (improve guess x)
  (average guess (exact->inexact (/ x guess))))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x)
                 x)))

(define (square x) (* x x))

(define (mysqrt x)
  (sqrt-iter 1.0 x))
問題1.6

ifが関数の場合、再帰を行おうとすると、展開する際に無限に展開される。

問題1.7

good-enough?を以下のようにする。ただ、iteratorの中で2回同じような処理を行うことになるので、そこが問題か。

(define (good-enough? guess x)
  (< (abs (- (improve guess x) x)) 0.001))
問題1.8
(define (good-enough? x y)
  (< (abs (- 1.0 (/ x y))) 0.001))

(define (improve y x)
  (/ (+ (/ x (square y)) (* y 2)) 3.0))
           
(define (cubic-root-iter old new x)
  (if (good-enough? old new)
      new
      (cubic-root-iter new (improve new x)
                 x)))

(define (square x) (* x x))
(define (cube x) (* x x x))

(define (cubic-root x)
  (cubic-root-iter 1.0 x x))
問題1.8をブロック化
(define (cubic-root x)
  (define (good-enough? x y)
    (< (abs (- 1.0 (/ x y))) 0.001))
  (define (improve y x)
    (/ (+ (/ x (square y)) (* y 2)) 3.0))
  (define (cubic-root-iter old new x)
    (if (good-enough? old new)
        new
        (cubic-root-iter new (improve new x)
                 x)))
  (define (square x) (* x x))
  (cubic-root-iter 1.0 x x))

ブロック化すると、ブロック外からはブロック内の手続き(cubic-root-iter etc.)は使用不可能。