Skip to content

Latest commit

 

History

History
39 lines (29 loc) · 1.04 KB

2.22.md

File metadata and controls

39 lines (29 loc) · 1.04 KB

2.22

Question

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

(cons (square (car things)) answer) places the subsequent answer before the predecessor, resulting in a reversed list.

The second attempt uses the right order but leads with nil: this should be a base case instead.