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:
(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.
练习 1.6:Alyssa P. Hacker 不明白为什么 if 需要作为特殊形式提供。“为什么我不能直接用 cond 将它定义为一个普通的过程呢?”她问道。Alyssa 的朋友 Eva Lu Ator 声称这确实可以做到,并定义了一个新版本的 if:
(define (new-if predicate
then-clause
else-clause)
(cond (predicate then-clause)
(else else-clause)))
Eva 向 Alyssa 演示了这个程序:
(new-if (= 2 3) 0 5)
5
(new-if (= 1 1) 0 5)
0
受此鼓舞,Alyssa 用 new-if 重写了平方根程序:
(define (sqrt-iter guess x)
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x) x)))
当 Alyssa 试图用这个程序计算平方根时,会发生什么?请解释。
(define (new-if predicate
then-clause
else-clause)
(cond (predicate then-clause)
(else else-clause))) (new-if (= 2 3) 0 5)
5
(new-if (= 1 1) 0 5)
0 (define (sqrt-iter guess x)
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x) x)))