my attempt to do the exercises in sicp.

Wednesday, July 16, 2008

sicp exercise 2.22


; Exercise 2.22.  Louis Reasoner tries to rewrite the first square-list procedure of exercise 2.21 so that it evolves an iterative process:

; (define (square-list items)
;   (define (iter things answer)
;     (if (null? things)
;         answer
;         (iter (cdr things)
;               (cons (square (car things))
;                     answer))))
;   (iter items nil))

; Unfortunately, defining square-list this way produces the answer list in the reverse order of the one desired. Why?

; Louis then tries to fix his bug by interchanging the arguments to cons:

; (define (square-list items)
;   (define (iter things answer)
;     (if (null? things)
;         answer
;         (iter (cdr things)
;               (cons answer
;                     (square (car things))))))
;   (iter items nil))

; This doesn't work either. Explain.

; Answer:
; Because the first algorith starts with nil and adds elements to the list beginning from the head of input list. So the resulting list is reversed.
; In the second method, although the items are in the same order, it doesnt produce a list at all.

No comments: