Exercise 1.6

What is the difference between the special-form if procedure that is provided, and this new-if, defined in terms of cond:

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

In some cases, new-if works the same as if:

(new-if (= 2 3) 0 5)
5

(new-if (= 1 1) 0 5)
0

What happens when we use new-if in the following sqrt-iter procedure?

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

(define (improve guess x)
  (average guess (/ x guess)))

(define (average x y)
  (/ (+ x y) 2))

(define (good-enough? guess x)
  (< (abs (- (* guess guess) x)) 0.001))

(define (sqrt x)
  (sqrt-iter 1.0 x))

if is a special form that evaluates the consequent or the alternate expressions, but not both. new-if, on the other hand, is a regular procedure and is thus evaluated in applicative order. In this case new-if will attempt to call sqrt-iter recursively even in the base case, resulting in an infinite recursion. See also this explanation.

Back to exercises