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