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 (element-of-set? x set)
11 (cond ((null? set) false)
12 ((= x (car set)) true)
13 ((< x (car set)) false)
14 (else (element-of-set? x (cdr set)))))
15 (define (intersection-set set1 set2)
16 (if (or (null? set1) (null? set2))
17 '()
18 (let ((x1 (car set1)) (x2 (car set2)))
19 (cond ((= x1 x2) (cons x1
20 (intersection-set (cdr set1)
21 (cdr set2))))
22 ((< x1 x2) (intersection-set (cdr set1)
23 set2))
24 ((> x1 x2) (intersection-set set1
25 (cdr set2)))))))
27 ;; Exercise 2.61. Give an implementation of adjoin-set using the ordered representation. By analogy with element-of-set? show how to take advantage of the ordering to produce a procedure that requires on the average about half as many steps as with the unordered representation.
29 (define (adjoin-set x set)
30 (cond ((null? set) (list x))
31 ((= x (car set)) set)
32 ((< x (car set)) (cons x set))
33 (else (cons (car set) (adjoin-set x (cdr set))))))
35 (test-case (adjoin-set 5 '()) '(5))
36 (test-case (adjoin-set 5 '(1 2 3 4 5)) '(1 2 3 4 5))
37 (test-case (adjoin-set 5 '(1 2 3 4)) '(1 2 3 4 5))
38 (test-case (adjoin-set 5 '(6 7 8 9)) '(5 6 7 8 9))
39 (test-case (adjoin-set 5 '(1 2 3 4 6 7 8 9)) '(1 2 3 4 5 6 7 8 9))
41 ;; Exercise 2.62. Give a (n) implementation of union-set for sets represented as ordered lists.
43 (define (union-set set1 set2)
44 (cond ((null? set1) set2)
45 ((null? set2) set1)
46 (else
47 (let ((x1 (car set1))
48 (x2 (car set2)))
49 (cond ((= x1 x2) (cons x1 (union-set (cdr set1) (cdr set2))))
50 ((< x1 x2) (cons x1 (union-set (cdr set1) set2)))
51 ((> x1 x2) (cons x2 (union-set set1 (cdr set2)))))))))
53 (test-case (union-set '(1 2 3 4 5) '(2 3 4)) '(1 2 3 4 5))
54 (test-case (union-set '(1 2 3) '()) '(1 2 3))
55 (test-case (union-set '() '(1 2 3)) '(1 2 3))
56 (test-case (union-set '(1 2 3 4 5) '(6 7 8 9 10)) '(1 2 3 4 5 6 7 8 9 10))
57 (test-case (union-set '(1 3 5 7) '(2 3 4 5)) '(1 2 3 4 5 7))