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.
练习 2.22:Louis Reasoner 试图重写练习 2.21 中的第一个 square-list 过程,使其产生一个迭代型计算过程:
(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 所产生的答案表的顺序与期望的相反。为什么?
Louis 随后试图通过交换传给 cons 的两个参数来修正这个错误:
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons answer
(square
(car things))))))
(iter items nil))
这样同样不行。请解释原因。
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons (square (car things))
answer))))
(iter items nil)) (define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons answer
(square
(car things))))))
(iter items nil))