views:

253

answers:

3

I'm just beginning to work through SICP (on my own; this isn't for a class), and I've been struggling with Exercise 1.4 for a couple of days and I just can't seem to figure it out. This is the one where Alyssa re-defines if in terms of cond, like so:

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

She tests it successfully on some simple cases, and then uses it to re-write the square root program (which worked just fine with if):

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

The question then asks: "What happens when Alyssa attempts to use this to compute square roots? Explain." [If necessary, I'm happy to reproduce the 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 recurs (executes recursively? What's the verb form of "recursive"?) infinitely. I just can't explain why this happens. Whatever subtle difference exists between if and new-if is eluding me. Any and all help much appreciated.

+2  A: 

new-if is a function. When a function is called, what's the first thing that Scheme does with the argument list? It evaluates all the arguments.

Greg Hewgill
A: 

I don't know the answer to your question but the word you are looking for is "recurses" :-)

Vicky
+1  A: 

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

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

To evaluate an if expression, the interpreter starts by evaluating the <predicate> part of the expression. If the <predicate> evaluates to a true value, the interpreter then evaluates the <consequent> and returns its value. Otherwise it evaluates the <alternative> and returns its value.

alex vasi