Geek-Side

Resource > SICP Exersise 2_66


Exersise 2.66

  (define (lookup given-key set-of-records)
    (cond [(null? set-of-records) #f]
      [(< 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))]
          [(equal? given-key (key (entry set-of-records)))
           (entry set-of-records)]))
  
  (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 (key x) x)
  
  (use gauche.test)
  (test-start "Excersse 2.66")
  (define tree1
    (make-tree 7 (make-tree 3 (make-tree 1 '() '())
                              (make-tree 5 '() '()))
                 (make-tree 9 '()
                              (make-tree 11 '() '()))))
  (test* "normal" '1 (lookup '1 tree1))
  (test* "normal" '7 (lookup '7 tree1))
  (test* "normal" #f (lookup '2 tree1))
  (test-end)