excercise-1.6

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:

1
2
3
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))

Eva demonstrates the program for Alyssa:

1
2
3
4
(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:

1
2
3
4
(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.

Ans: 原来的 if 语句对 predicate 进行判断之后再决定计算哪个分支,而 new-if 由于编译器是应用序执行程序,无论 predicate 的值是什么,都会对两个分支进行计算.