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)     

In "normal order" (as described in first chapter) Scheme this procedure should also loop forever. Since normal order does not necessarily means lazy.

So normal order evaluation expands procedures and arguments to most primitive form and only then evaluate it. In this case evaluator would keep expanding (factorial (- n 1)) forever.