Blob


1 (define (test-case actual expected)
2 (newline)
3 (display "Actual: ")
4 (display actual)
5 (newline)
6 (display "Expected: ")
7 (display expected)
8 (newline))
10 (define (filter predicate sequence)
11 (cond ((null? sequence) '())
12 ((predicate (car sequence))
13 (cons (car sequence)
14 (filter predicate (cdr sequence))))
15 (else (filter predicate (cdr sequence)))))
16 (define (accumulate op initial sequence)
17 (if (null? sequence)
18 initial
19 (op (car sequence)
20 (accumulate op initial (cdr sequence)))))
21 (define (enumerate-interval low high)
22 (if (low > high)
23 '()
24 (cons low (enumerate-interval (1+ low) high))))
25 (define (enumerate-tree tree)
26 (cond ((null? tree) '())
27 ((not (pair? tree)) (list tree))
28 (else (append (enumerate-tree (car tree))
29 (enumerate-tree (cdr tree))))))
31 ;; Exercise 2.33. Fill in the missing expressions to complete the following definitions of some basic list-manipulation operations as accumulations:
33 (define (map p sequence)
34 (accumulate (lambda (x y)
35 (cons (p x) y))
36 '()
37 sequence))
39 (test-case (map square '()) '())
40 (test-case (map square '(1)) '(1))
41 (test-case (map square '(1 2 3 4 5)) '(1 4 9 16 25))
43 (define (append seq1 seq2)
44 (accumulate cons
45 seq2
46 seq1))
48 (test-case (append '() '()) '())
49 (test-case (append '(1 2 3) '()) '(1 2 3))
50 (test-case (append '() '(4 5 6)) '(4 5 6))
51 (test-case (append '(1 2 3) '(4 5 6)) '(1 2 3 4 5 6))
52 (test-case (append '((1 (2)) 3) '((4 ((5)) 6))) '((1 (2)) 3 (4 ((5)) 6)))
54 (define (length sequence)
55 (accumulate (lambda (first accum)
56 (1+ accum))
57 0
58 sequence))
60 (test-case (length '()) 0)
61 (test-case (length '(1 2 3)) 3)
62 (test-case (length '((1 (2)) 3 (4 ((5)) 6))) 3)