Reputation: 492
I am doing ex2.22 of SICP, the exercise gives a procedure which intends to square a list but the output reverses the list. But when I type it in DrRacket the output is unexpected. The code:
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons (square (car things))
answer))))
(iter items null))
(square-list (list 1 2 3))
The expected output is (9 4 1) but actually it is '(#<procedure> #<procedure> #<procedure>)
.I just don't know why.
Upvotes: 0
Views: 71
Reputation: 27414
The result depends on the definition of square
, that you have probably defined in a wrong way. Here is the right definition of square
that returns the correct answer:
(define (square item)
(* item item))
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons (square (car things))
answer))))
(iter items null))
(square-list (list 1 2 3))
(9 4 1)
Here you can also note that the result, given the way in which you calculate it, is reversed with respect to the original list. If you want to obtain it in the same order you could add, for instance, a reverse at the end of the call of iter
:
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons (square (car things))
answer))))
(reverse (iter items null)))
Upvotes: 3