Exercise 1.6. why if needs to be provided as aspecial form. ``Why can't I just define it as an ordinary procedure in terms of cond?''
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
没有必要那么复杂:
(define (iter x)
(new-if (#t )
0
(iter x)))
(iter 2)
What happens when Alyssa attempts to use this to compute square roots?Explain.
new-if是普通函数,采用应用序。求值( new-if (#t ) 0 (iter x) )时,需要先求出参数的值,而(iter x)又进入下一轮应用序...导致超过最大递归深度,栈溢出。
if采用正则序,如果将上面的代码改成if (#t ) ,出现新的错误。
换言之,在new-if (#t ) 时,完全没有机会发现那个错误。fix:if #t
Exercise 1.7. The good-enough? test used in computing square roots will not bevery effective for finding the square roots of very small numbers.Also, in real computers, arithmetic operations are almost always performed with limited precision. This makes our test inadequate forvery large numbers. Explain these statements, with examples showinghow the test fails for small and large numbers. An alternativestrategy for implementinggood-enough? is to watch how guess changes from one iteration to the next and to stop when thechange is a very small fraction of the guess. Design a square-rootprocedure that uses this kind of end test. Does this work better forsmall and large numbers?
这个问题在一些讨论double的书中都有提到。太小的数,两次的差异可能超出double的精度,好像没有变化;太大的数,精度又不足以表示两个大数之差。