Alyssa P. Hacker doesn't see why

Eva demonstrates the program for Alyssa:

5

0

Delighted, Alyssa uses new-if to rewrite the square-root program:

What happens when Alyssa attempts to use this to compute square roots? Explain.

As per Exercise 1.5, this will result in an infinite loop (or, more precisely, you run out of stack space). Why does an infinite loop occur in the

`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.

As per Exercise 1.5, this will result in an infinite loop (or, more precisely, you run out of stack space). Why does an infinite loop occur in the

`sqrt-iter`, but not in the first two examples? This is simply a matter of applicative-order being a problem. Since in the first two cases both the consequent and the alternative can be fully evaluated,`new-if`happily evaluates them, and then evaluates the if of the predicate, returning the appropriate result. In the`sqrt-iter`case, however, the alternative is evaluated. Normally this is not a problem since the recursion is short circuited by the base case. However since the alternative is ALWAYS evaluated, regardless of whether or not it is the appropriate return of`new-if`, an infinite loop results.Leave a comment