SICP Exercise 1.20

Question

The process that a procedure generates is of course dependent on the rules used by the interpreter. As an example, consider the iterative gcd procedure given above. Suppose we were to interpret this procedure using normal-order evaluation, as discussed in 1.1.5. (The normal-order-evaluation rule for if is described in Exercise 1.5.) Using the substitution method (for normal order), illustrate the process generated in evaluating (gcd 206 40) and indicate the remainder operations that are actually performed. How many remainder operations are actually performed in the normal-order evaluation of (gcd 206 40)? In the applicative-order evaluation?

Answer

Normal-order:

(gcd 206 40)

(if (= 40 0)
    206
    (gcd 40 (remainder 206 40)))

(if (= (remainder 206 40) 0) ; 1 eval
    40
    (gcd (remainder 206 40) (remainder 40 (remainder 206 40))))

(if (= (remainder 40 (remainder 206 40)) 0) ; 2 evals
    (remainder 206 40)
    (gcd 
      (remainder 40 (remainder 206 40))
      (remainder 
        (remainder 206 40)
        (remainder 40 (remainder 206 40)))))

(if (= (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) 0) ; 4 evals
    (remainder 40 (remainder 206 40))
    (gcd 
      (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))
      (remainder 
        (remainder 40 (remainder 206 40))
        (remainder (remainder 206 40) (remainder 40 (remainder 206 40))))))

(if (= (remainder 
         (remainder 40 (remainder 206 40))
         (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))) 0) ; 7 evals
       (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))
       (gcd 
         ; long and irrelevant parts of code
       )
)

(remainder (remainder 206 40) (remainder 40 (remainder 206 40))) ; 2 evals
(remainder 6 (remainder 40 6)) ; 1 eval
(remainder 6 4) ; 1 eval
2

The only remainders which are actually calculated here are those contained within the consequents, i.e. the first clauses after the conditional clause, and within the statement which is ultimately evaluated, i.e. reduced. The total number of evaluated remainders is $18$ for normal-order evaluation.

Applicative-order:

(gcd 206 40)
(gcd 40 (remainder 206 40)) ; 1 eval
(gcd 40 6)
(gcd 6 (remainder 40 6)) ; 1 eval
(gcd 6 4)
(gcd 4 (remainder 6 4)) ; 1 eval
(gcd 4 2)
(gcd 2 (remainder 4 2)) ; 1 eval
(gcd 2 0)
2

Here, the total number of evaluations is $4$.