2008年12月25日星期四

sicp习题解答1.1


;;Exercise.1.2
(/ (+ 5 4
(- 2 (- 3 (+ 6 (/ 4 5)))))
(* 3
(- 6 2)
(- 2 7)))

-37/150

;;Exercise 1.3.
(define (sum-of-max-two a b c)
(cond ((and (> b a) (> c a)) (+ b c)) ;; no a

((and (> a b) (> c b)) (+ a c)) ;; no b
(else (+ a b))))

;;[test]

(sum-of-max-two 4 5 5)
(sum-of-max-two 1 2 3)
(sum-of-max-two 3 2 1)
(sum-of-max-two 4 5 4)

;;Exercise 1.4.
(if (> b 0) + -) ;根据b的正负返回运算符+或-

;;Exercise 1.5.
应用序求值会死循环, 因为会先对参数求值, (p)不断调用自己.

正则序求值返回0, 因为(p)不会被展开.

;;Exercise 1.6.
如果把if定义成普通函数,则计算时,需要对实际参数进行求值,这会导致无限递归.


;;Exercise 1.7.
(define (good-enough? guess x)
(< (/ (abs (- guess
(improve guess x)))
guess)
0.000000000001))



;;Exercise 1.8.
(define (cube-root x)
(define (cube-root-iter guess x)
(if (good-enough? guess x)
guess
(cube-root-iter (improve guess x)
x)))
(cube-root-iter 1.0 x))

(define (improve guess x)
(/ (+ (/ x
(* guess guess))
(* guess 2))
3))


没有评论: