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 (define (square-list-map nums)
12 (map (lambda (x) (* x x)) nums))
14 (define (square-list-recurse nums)
15 (if (null? nums)
16 '()
17 (cons (* (car nums) (car nums))
18 (square-list-recurse (cdr nums)))))
20 ;; Exercise 2.22. Louis Reasoner tries to rewrite the first square-list procedure of exercise 2.21 so that it evolves an iterative process:
22 (define (square-list items)
23 (define (iter things answer)
24 (if (null? things)
25 answer
26 (iter (cdr things)
27 (cons (square (car things))
28 answer))))
29 (iter items nil))
31 ;; (cons (square (car things))
32 ;; answer)
33 ;; puts the next number in front of its previous number, but we should be
34 ;; putting the next number behind the previous number
35 ;; that's why the numbers appear reversed in the resulting list
37 ;; Louis then tries to fix his bug by interchanging the arguments to cons:
39 (define (square-list items)
40 (define (iter things answer)
41 (if (null? things)
42 answer
43 (iter (cdr things)
44 (cons answer
45 (square (car things))))))
46 (iter items nil))
48 ;; This doesn't work either. Explain.
50 ;; answer is a list whereas (square (car things)) is a number. So although
51 ;; the order is right, you end up with nested lists. We should instead be
52 ;; using (append answer (list (square (car things))))
53 ;; to append two lists
55 (define (test-case actual expected)
56 (load-option 'format)
57 (newline)
58 (format #t "Actual: ~A Expected: ~A" actual expected))