-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.66.rkt
48 lines (35 loc) · 1.47 KB
/
2.66.rkt
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
#lang sicp
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
; every entry has a key and a value
(define (entry-key entry) (car entry))
(define (entry-value entry) (cdr entry))
(define (make-entry key value)
(cons key value))
(define (make-tree entry left right)
(list entry left right))
; sorted by (numeric) key
(define (adjoin-set key value set)
(cond ((null? set) (make-tree (make-entry key value) '() '()))
((= key (entry-key (entry set))) (error "key exists"))
((< key (entry-key (entry set)))
(make-tree (entry set)
(adjoin-set key value (left-branch set))
(right-branch set)))
((> key (entry-key (entry set)))
(make-tree (entry set)
(left-branch set)
(adjoin-set key value (right-branch set))))))
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) false)
((= given-key (entry-key (entry set-of-records))) (entry set-of-records))
((< given-key (entry-key (entry set-of-records))) (lookup given-key (left-branch set-of-records)))
(else (lookup given-key (right-branch set-of-records)))))
(define tree (adjoin-set 1 3 '()))
(define tree2 (adjoin-set 5 6 tree))
(define tree3 (adjoin-set 7 8 tree2))
(entry-value (entry tree3))
(entry-value (entry (right-branch tree3)))
(entry-value (entry (right-branch (right-branch tree3))))
(lookup 7 tree3)