sicp-ex-2.22



<< Previous exercise (2.21) | Index | Next exercise (2.23) >>


jz

  
 (define nil '()) 
  
 (define (square-list items) 
   (define (iter things answer) 
     (if (null? things) 
         answer 
         (iter (cdr things) 
               (cons (square (car things)) answer)))) 
   (iter items nil)) 
  
 (square-list (list 1 2 3 4)) 
  
 ;; The above doesn't work because it conses the last item from the 
 ;; front of the list to the answer, then gets the next item from the 
 ;; front, etc. 
  
 (define (square-list items) 
   (define (iter things answer) 
     (if (null? things) 
         answer 
         (iter (cdr things) 
               (cons answer (square (car things)))))) 
   (iter items nil)) 
  
 (square-list (list 1 2 3 4)) 
  
 ;; This new-and-not-improved version conses the answer to the squared 
 ;; value, but the answer is a list, so you'll end up with (list (list 
 ;; ...) lastest-square). 
  

shyam

Saying in a different way, the bug on the second version can also be attributed to the property of cons as shown below.

1 ]=> (cons 1 2)

;Value 11: (1 . 2)

1 ]=> (cons 1 (list 2 3))

;Value 12: (1 2 3)

1 ]=> (cons (list 2 3) 1)

;Value 13: ((2 3) . 1)