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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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) | |