What is the explanation of exercise 1.6 in SICP?

I am just starting to work through SICP (by itself, this is not for the class), and I struggled with exercise 1.6 for a couple of days, and I just can’t understand what it is outside. This is where Alyssa redefines if in terms of cond , for example:

 (define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause)) 

She successfully tests it in some simple cases, and then uses it to re-write a program with a square root (which works fine with if ):

 (define (sqrt-iter guess x) (new-if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) 

Then the question arises: "What happens when Alyssa tries to use this to calculate the square roots? Explain." [If necessary, I am happy to reproduce other procedures ( good-enough? improve , etc.), just let me know.]

Now I know what happens: it never returns a value, which means that the program is infinitely recursive. I just can't explain why this is happening. Whatever the subtle difference between if and new-if , eludes me. Any help is greatly appreciated.

+47
recursion sicp
Jul 23 '09 at 11:53
source share
3 answers

new-if is a function. When a function is called, what is the first thing Scheme does with an argument list? He appreciates all the arguments.

+61
Jul 23 '09 at 11:55
source share

new-if is a procedure, and the scheme uses the applicative order estimate (1.1.5), so even before new-if is executed, it must first evaluate all arguments that are guess and (sqrt-iter (improve guess x) x) . You can see that the last argument is a recursion that calls the new new-if procedure, so an endless loop happens.

The usual if should not evaluate its arguments first, just go along the path, this is the difference between if and new-if . :)

+28
Dec 12 '11 at 12:36
source share

First of all, you must understand the difference between the evaluation of the application order and the usual order. Lisp uses the applicative order, but conditional expressions are not evaluated as normal functions ( sicp chapter 1.1.6 ):

 (if <predicate> <consequent> <alternative>) 

To evaluate an if expression, the interpreter begins by evaluating the <predicate> expression. If the <predicate> value matches the true value, the interpreter then evaluates the <consequent> value and returns its value. Otherwise, it evaluates the <alternative> value and returns its value.

+20
Jul 23 '09 at 13:04
source share



All Articles