[archives] [homepage]

Problem 2.22
Friday, August 23, 2019; ago; Download .md

SICP Exercise 2.22

This implementation of square-list is basically an extension of the reverse procedure. The difference being that the elements are squared before consed.

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

The procedure begins with an empty list. The first item in things is squared and consed as the last element of result.

The second implementation:

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

Produces the following:

> (square-list-2 (list 1 2 3 4 5))
(((((() . 1) . 4) . 9) . 16) . 25)

Which is not a list. The order has been fixed but cons builds a pair of answer and the square of next element in things.