SICP読書録その2

夏休み前からちょくちょくやっているのでメモってみる。

ex. 1.6

早速だが分からない。condを使ってifを再実装したときの問題点。
恐らく、p.19の補足項目あたりが怪しいけど。。。

A minor difference between if and cond is that the part of each cond clause may be a sequence of expressions. If the corresponding is found to be true, the expressions are evalueated in sequence and the value of the final expression in the sequence is returened as the value of cond. In an if expression, however, the and must be single expression.

ここでいうおよびはif構文についてものも。

(if <predicate> <consequence> <alternative>)

分からない問題は無視の方向で。
まぁ、前回も分からなかったからとばす。


ex. 1.7

誤差を絶対誤差でなく、相対誤差にすればいいんでない?

(define (good-enough? guess x)
  ;; 0.001 -> (/ x 1000)
  (< (abs (- (sq guess) x)) (/ x 1000)))

ex. 1.8

立方根をニュートン法で解く問題。特に迷うところはない。
どうしてもgood-enough?のところで(abs (- guess x))としてしまう。

近似値は次式の通り。
\frac{x/y^2+2y}{3}

(define (cb x) (* x x x))

(define (cube-root x)
  (define (good-enough? guess)
    (< (abs (- (cb guess) x)) (/ x 1000)))
  (define (improve guess)
    (/ (+ (/ x (sq guess))
	  (* 2 guess))
       3))	  
  (define (cbrt-iter guess)
    (if (good-enough? guess)
	guess
	(cbrt-iter (improve guess))))
  (cbrt-iter 1.0))

ex. 1.11

n<3に対し、f(n)=n, n>=3に対してf(n)=f(n-1)+2f(n-2)+3f(n-3)となる関数fを計算する手続きを書く。
まず再帰を用いた方法。

(define (ex1.11rec n)
  (if (and (< 0 n) (< n 4))
      n
      (+ (pro1.11 (- n 1))
	 (* 2 (ex1.11rec (- n 2)))
	 (* 3 (ex1.11rec (- n 3))))))

次に繰り返しを用いた方法。
状態を保持すればいいんだよな。

(define (ex1.11-2 n)
  (define (iter a b c n)
    (cond ((= n 1) c)
	  ((= n 2) b)
	  ((= n 3) a)
	  (else (iter (+ a (* 2 b) (* 3 c)) a b (- n 1)))))
  (iter 3 2 1 n))


再帰を用いた方法ではifの判定で0

(define (ex1.11-2 n)
  (define (iter a b c n)
    (cond ((= n 1) n) ;; 間違い
	  ((= n 2) n) ;; 間違い
	  ((= n 3) n) ;; 間違い
	  (else (iter (+ a (* 2 b) (* 3 c)) a b (- n 1)))))
  (iter 3 2 1 n))

ex. 1.12

Pascal三角形を求めればいい問題。
これは、各段階の全要素が必要なのかな?
そうでないと逆に難しそうか?