sicp 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.

 

第一个程序是显然的,(cons (square (car things)) answer),结果当然是逆序的。

第二个程序,(cons answer (square (car things))),由于cons的第一个参数是列表,第二个参数是数,所以结果并不是一个列表,而是((((() . 1) . 4) . 9) . 16)

 

遵照原思路,应该使用append,正确的程序是

 

 

(define (square-list items)
  (define (iter things answer)
    (if (null? things)
        answer
        (iter (cdr things)
              (append answer (list (square (car things)))))))
  (iter items '()))

(define (square x)
  (* x x))

(square-list '(1 2 3 4))
 

 

 

你可能感兴趣的:(SICP)