(define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause))) (define (sqrt-iter guess x) (new-if (good-enough? guess x) guess (sqrt-iter (improve guess x) x)))
sqrt-iter will never terminate.
The first time new-if
is called it is passed two arguments, guess
and (sqrt-iter (improve guess x) x)
.
Scheme uses applicative order evaluation and so another call to sqrt-iter will be evaluated resulting in the following behaviour which won’t terminate:
sqrt-iter new-if sqrt-iter new-if ... ...
[…] Comment Posted by Barry Allison on 5th January, 2011 This is the same problem we saw with if in Exercise 1.6. In an applicative order language the factorial procedure will never terminate. Since both branches […]
Apologies for responding to a comment several years old.
I think I understand the explanation, but I’m not sure why this does not when using “if” rather than “new-if”. What does the “new-if” do that a regular “if” does not?
new-if isn’t doing anything special.
When you use new-if though scheme evaluates *all* of the arguments, predicate, then-clause and else-clause.
But, scheme’s built-in if works differently. First predicate gets evaluated and only then will then-clause or else-clause get evaluated – not both of them. The book hasn’t explained how to do that yet, but it’s covered in great detail in a later chapter and you’ll see how to do just that.
But how is this case different from Exercise 1.5. where built-in “if” gets puts into infinite loop because of applicative-order evaluation?
Both demonstrate applicative order’s eager evaluation. I think this exercise is designed to show how and shy scheme’s built in if behaves differently.