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 (scale-tree tree factor)
11 (cond ((null? tree) '())
12 ((not (pair? tree)) (* factor tree))
13 (else (cons (scale-tree (car tree) factor)
14 (scale-tree (cdr tree) factor)))))
16 (define (scale-tree tree factor)
17 (map (lambda (sub-tree)
18 (if (pair? sub-tree)
19 (scale-tree sub-tree factor)
20 (* factor sub-tree)))
21 tree))
23 (define (square-tree tree)
24 (cond ((null? tree) '())
25 ((not (pair? tree)) (* tree tree))
26 (else (cons (square-tree (car tree))
27 (square-tree (cdr tree))))))
29 ;; (test-case (square-tree
30 ;; (list 1
31 ;; (list 2 (list 3 4) 5)
32 ;; (list 6 7)))
33 ;; '(1 (4 (9 16) 25) (36 49)))
35 ;; (define (square-tree-map tree)
36 ;; (map (lambda (sub-tree)
37 ;; (if (pair? sub-tree)
38 ;; (square-tree-map sub-tree)
39 ;; (* sub-tree sub-tree)))
40 ;; tree))
42 ;; (test-case (square-tree-map
43 ;; (list 1
44 ;; (list 2 (list 3 4) 5)
45 ;; (list 6 7)))
46 ;; '(1 (4 (9 16) 25) (36 49)))
48 ;; Exercise 2.31. Abstract your answer to exercise 2.30 to produce a procedure tree-map with the property that square-tree could be defined as
50 (define (tree-map proc tree)
51 (cond ((null? tree) '())
52 ((not (pair? tree)) (proc tree))
53 (else (cons (tree-map proc (car tree))
54 (tree-map proc (cdr tree))))))
56 (define (square-tree-map tree) (tree-map square tree))
58 (test-case (square-tree-map
59 (list 1
60 (list 2 (list 3 4) 5)
61 (list 6 7)))
62 '(1 (4 (9 16) 25) (36 49)))
65 ;; Exercise 2.32. We can represent a set as a list of distinct elements, and we can represent the set of all subsets of the set as a list of lists. For example, if the set is (1 2 3), then the set of all subsets is (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)). Complete the following definition of a procedure that generates the set of subsets of a set and give a clear explanation of why it works:
67 (define (subsets s)
68 (if (null? s)
69 (list nil)
70 (let ((rest (subsets (cdr s))))
71 (append rest (map <??> rest)))))