Special form

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.


    # Brian Hagerty
    2 years ago

    The book doesn't prepare us for this question. Readers will likely think the issue is a difference between if and cond; it's not. The issue is that wrapping cond in a function changes how arguments are evaluated. When a function is evaluated, its arguments are evaluated right away. But it's impossible to evaluate the arguments to new-if, because sqr-iter simply calls itself repeatedly. See https://stackoverflow.com/questions/1171252/whats-the-explanation-for-exercise-1-6-in-sicp

Authentication required

You must log in to post a comment.

Login