Blob


1 (define (map proc items)
2 (if (null? items)
3 '()
4 (cons (proc (car items))
5 (map proc (cdr items)))))
7 (define (scale-list items factor)
8 (map (lambda (x) (* x factor))
9 items))
11 ;; Exercise 2.21. The procedure square-list takes a list of numbers as argument and returns a list of the squares of those numbers.
13 (define (square-list-map nums)
14 (map (lambda (x) (* x x)) nums))
16 (define (square-list-recurse nums)
17 (if (null? nums)
18 '()
19 (cons (* (car nums) (car nums))
20 (square-list-recurse (cdr nums)))))
22 (define (test-case actual expected)
23 (load-option 'format)
24 (newline)
25 (format #t "Actual: ~A Expected: ~A" actual expected))
27 (test-case (square-list-recurse (list 1 2 3 4)) '(1 4 9 16))
28 (test-case (square-list-map (list 1 2 3 4)) '(1 4 9 16))
30 Exercise 2.22. Louis Reasoner tries to rewrite the first square-list procedure of exercise 2.21 so that it evolves an iterative process:
32 (define (square-list items)
33 (define (iter things answer)
34 (if (null? things)
35 answer
36 (iter (cdr things)
37 (cons (square (car things))
38 answer))))
39 (iter items nil))
41 Unfortunately, defining square-list this way produces the answer list in the reverse order of the one desired. Why?
43 Louis then tries to fix his bug by interchanging the arguments to cons:
45 (define (square-list items)
46 (define (iter things answer)
47 (if (null? things)
48 answer
49 (iter (cdr things)
50 (cons answer
51 (square (car things))))))
52 (iter items nil))
54 This doesn't work either. Explain.