Exercise 3.24.  In the table implementations above, the keys are tested for equality using equal? (called by assoc). This is not always the appropriate test. For instance, we might have a table with numeric keys in which we don’t need an exact match to the number we’re looking up, but only a number within some tolerance of it. Design a table constructor make-table that takes as an argument a same-key? procedure that will be used to test “equality” of keys. Make-table should return a dispatch procedure that can be used to access appropriate lookup and insert! procedures for a local table.

 


(define (make-table same-key?)
(let
((table (list '*table*)))
(define (lookup key)
(let
((record (assoc key (cdr table))))
(if
record
;; (cdr record)
record
false)))
(define (assoc key records)
(cond
((null? records)
false)
((same-key?
key
(caar records))
(car records)
(newline)
(display (list records (car records))))
(else
(assoc key (cdr records)))))
(define (insert! key value)
(let ((record (assoc key (cdr table))))
(if
record
(set-cdr! record value)
(set-cdr!
table
(cons (cons key value) (cdr table)))))
'ok)
(define (print-table)
table)
(define (dispatch m)
(cond
((eq? m 'lookup) lookup)
((eq? m 'insert!) insert!)
((eq? m 'print-table) (print-table))
(else
(error "Bad request" m))))
dispatch))
(define t1 (make-table eq?))
((t1 'insert!) 'a 1)
((t1 'insert!) 'b 2)
((t1 'insert!) 'c 3)
(t1 'print-table)
((t1 'lookup) 'a)
((t1 'lookup) 'b)
((t1 'lookup) 'c)

view raw

s324.scm

hosted with ❤ by GitHub

 

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading