Exercise 1.6. Alyssa P. Hacker doesn't see why if needs to be provided as a special form. ``Why
can't I just define it as an ordinary procedure in terms of cond?'' she asks. Alyssa's friend Eva Lu
Ator claims this can indeed be done, and she defines a new version of if:
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
Eva demonstrates the program for Alyssa:
(new-if (= 2 3) 0 5)
5
(new-if (= 1 1) 0 5)
0
Delighted, Alyssa uses new-if to rewrite the square-root program:
32(define (sqrt-iter guess x)
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
What happens when Alyssa attempts to use this to compute square roots? Explain.
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else-clause)))
(define (average x y)
(/ (+ x y) 2))
(define (improve guess x)
(average guess (/ x guess)))
(define (good-enough? guess x)
(< (abs (- (square guess) x))0.001))
(define (square x)
(* x x))
(define (sqrt-iter guess x)
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
sqrt-iter (improve guess x)作为参数来传递给new-if,在执行new-if的时候,就总是会执行sqrt-iter (improve guess x),造成了死循环。
posted on 2009-03-06 15:19
lzj520 阅读(297)
评论(0) 编辑 收藏 所属分类:
个人学习日记 、
sicp