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.
今天中午午休的时候想了很久想不出来,后来看了下网上另一个人的解释,如下
我开始的时候想的是,第一次是展开成
然后这个expression的结果我想成了是(inc 2 5),把new-if当成了if,按这样想下去,应该到(inc 5 5)的时候就该停止了,呵呵 :oops: 其实是应该展开成上面的表达式后,会继续去eval ,(inc 2 5),然后遇到new-if,在去(inc 3 5),最后就栈溢出了,看来还是脑子太久没转了, :cry:
(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.
今天中午午休的时候想了很久想不出来,后来看了下网上另一个人的解释,如下
(define (inc x y)
(new-if (= x y)
0
(inc (+ x 1) y)))
(inc 1 5)
我开始的时候想的是,第一次是展开成
(new-if (= 1 5)
0
(inc 2 5))
然后这个expression的结果我想成了是(inc 2 5),把new-if当成了if,按这样想下去,应该到(inc 5 5)的时候就该停止了,呵呵 :oops: 其实是应该展开成上面的表达式后,会继续去eval ,(inc 2 5),然后遇到new-if,在去(inc 3 5),最后就栈溢出了,看来还是脑子太久没转了, :cry: