-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path2.65.ss
73 lines (62 loc) · 2.33 KB
/
2.65.ss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(define (make-tree entry left-tree right-tree)
(list entry left-tree right-tree))
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
(else
(let ((x1 (car set1)) (x2 (car set2)))
(cond ((= x1 x2)
(cons x1 (union-set (cdr set1) (cdr set2))))
((< x1 x2)
(cons x1 (union-set (cdr set1) set2)))
((> x1 x2)
(cons x2 (union-set set1 (cdr set2)))))))))
(define (intersection-set set1 set2)
(if (or (null? set1) (null? set2))
'()
(let ((x1 (car set1)) (x2 (car set2)))
(cond ((= x1 x2)
(cons x1
(intersection-set (cdr set1) (cdr set2))))
((< x1 x2)
(intersection-set (cdr set1) set2))
((> x1 x2)
(intersection-set set1 (cdr set2)))))))
(define (tree->list tree)
(if (null? tree)
'()
(append (tree->list (left-branch tree))
(cons (entry tree)
(tree->list (right-branch tree))))))
(define (list->tree elements)
(car (partial-tree elements (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ left-size 1))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree (cdr non-left-elts) right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree this-entry left-tree right-tree)
remaining-elts))))))))
; set1 and set2 both tree
(define (union-set-tree set1 set2)
(let ((s1 (tree->list set1))
(s2 (tree->list set2)))
(list->tree (union-set s1 s2))))
(define (intersection-set-tree set1 set2)
(let ((s1 (tree->list set1))
(s2 (tree->list set2)))
(list->tree (intersection-set s1 s2))))
(define (op set1 set2)
(let ((s1 (tree->list set1))
(s2 (tree->list set2)))
(list->tree (op s1 s2))))