Anatoly
Anatoly

Reputation: 1916

What the difference between two if expression in Scheme?

I define a new version of if:

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

Then I use it as the following:

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

I understand that since the else-clause passed to new-if in the sqrt-iter procedure is always evaluated, sqrt-iter never stops making recursive calls to itself.

But I don't understand why we don't stop when good-enough? returns true => guess

Upvotes: 0

Views: 131

Answers (1)

C. K. Young
C. K. Young

Reputation: 223003

Your new-if is a procedure. Procedure arguments are evaluated before being passed to the procedure. Therefore, your recursive sqrt-iter call is going to be evaluated fully before new-if is called. As Robert Harvey commented, this results in infinite recursion.

Your new-if needs to be a macro to function correctly. Something like:

(define-syntax new-if
  (syntax-rules ()
    ((_ predicate then-clause else-clause)
     (cond (predicate then-clause)
           (else else-clause)))))

Upvotes: 5

Related Questions