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))
11 (define (element-of-set? x set)
12 (cond ((null? set) false)
13 ((equal? x (car set)) true)
14 (else (element-of-set? x (cdr set)))))
15 (define (adjoin-set x set)
16 (if (element-of-set? x set)
17 set
18 (cons x set)))
19 (define (intersection-set set1 set2)
20 (cond ((or (null? set1) (null? set2)) '())
21 ((element-of-set? (car set1) set2)
22 (cons (car set1)
23 (intersection-set (cdr set1) set2)))
24 (else (intersection-set (cdr set1) set2))))
25 (define (union-set set1 set2)
26 (cond ((null? set1) set2)
27 ((null? set2) set1)
28 ((element-of-set? (car set1) set2) (union-set (cdr set1) set2))
29 (else (cons (car set1) (union-set (cdr set1) set2)))))
31 (test-case (union-set '(1 2 3 4 5) '(1 3 4)) '(2 5 1 3 4))
33 ;; Exercise 2.60. We specified that a set would be represented as a list with no duplicates. Now suppose we allow duplicates. For instance, the set {1,2,3} could be represented as the list (2 3 2 1 3 2 2). Design procedures element-of-set?, adjoin-set, union-set, and intersection-set that operate on this representation. How does the efficiency of each compare with the corresponding procedure for the non-duplicate representation? Are there applications for which you would use this representation in preference to the non-duplicate one?
35 (define (element-of-set? x set)
36 (cond ((null? set) #f)
37 ((equal? x (car set)) #t)
38 (else (element-of-set? x (cdr set)))))
39 (test-case (element-of-set? 4 '(1 3 5 2 3 5 5)) #f)
40 (test-case (element-of-set? 3 '(1 3 5 2 3 5 5)) #t)
42 (define (adjoin-set x set)
43 (cons x set))
45 (test-case (adjoin-set 5 '()) '(5))
46 (test-case (adjoin-set 5 '(1 3)) '(5 1 3))
47 (test-case (adjoin-set 5 '(5 5 1 3)) '(5 5 5 1 3))
49 (define (union-set set1 set2)
50 (append set1 set2))
52 (test-case (union-set '(1 5 2 3 5) '(4 2 8 1 5)) '(1 5 2 3 5 4 2 8 1 5))
54 (define (intersection-set set1 set2)
55 (cond ((null? set1) set2)
56 ((null? set2) set1)
57 ((element-of-set? (car set1) set2)
58 (cons (car set1) (intersection-set (cdr set1) set2)))
59 (else (intersection-set (cdr set1) set2))))
61 (test-case (intersection-set '(1 5 2 3 5) '(4 2 8 1 5)) '(1 5 2 5 4 2 8 1 5))
63 ;; the new set has a lot of duplicated entries so that element-of-set? and
64 ;; intersection-set are much slower. The more duplicate entries, the slower
65 ;; they become. However, adjoin-set and union-set become extremely easy and
66 ;; fast to implement. You might use this representation when it is more
67 ;; important to be able to join two sets or add new elements to a set
68 ;; than it is to see if an element belongs to a set or is part of an
69 ;; intersection of two sets.