sicp-ex-4.25



<< Previous exercise (4.24) | Index | Next exercise (4.26) >>


meteorgan

  
  
  
 In applicative-order Scheme, when call (factorial 5), the call will not end. because, when call unless, even if (= n 1) is true, (factorial (- n 1)) will be called. so n will be 5, 4, 3, 2, 1, 0, -1 .... . In normal-order Scheme, this will work, Because normal-order Scheme uses lazy evaluation, when (= n 1) is true, (factorial n) will not be called. 

Here is an implementation in the underlying scheme to see that it indeed works this way.

 (define-macro (unless-lazy predicate action alternative) 
   `(if (not ,predicate) ,action ,alternative)) 
  
 (define (unless-applicative predicate action alternative) 
   (if (not predicate) action alternative)) 
  
 (define (factorial n) 
   (unless-applicative (= n 1) 
           (* n (factorial (- n 1))) 
           1)) 
          
 (factorial 5)