-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathex2.66-loopup-with-binary-tree.scm
35 lines (29 loc) · 1.44 KB
/
ex2.66-loopup-with-binary-tree.scm
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
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right) (list entry left right))
(define (list->tree 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))))))))
(car (partial-tree elements (length elements))))
(define key car)
(define value cadr)
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) '())
((equal? given-key (key (entry set-of-records))) (value (entry set-of-records)))
((< given-key (key (entry set-of-records))) (lookup given-key (left-branch set-of-records)))
((> given-key (key (entry set-of-records))) (lookup given-key (right-branch set-of-records)))))
(lookup 4 (list->tree '((1 "alpha") (2 "non") (3 "negative") (4 "are") (5 "str"))))