Blob


1 ;; Exercise 3.25. Generalizing one- and two-dimensional tables, show how to implement a table in which values are stored under an arbitrary number of keys and different values may be stored under different numbers of keys. The lookup and insert! procedures should take as input a list of keys used to access the table.
3 ;; we could actually keep the procedure as-is, by treating the list of keys as a single key and comparing equality of lists. The downside to this is that there would be no organization based on keys.
5 (define (lookup key table)
6 (let ((record (assoc key (cdr table))))
7 (if record
8 (cdr record)
9 false)))
10 (define (assoc key records)
11 (cond ((null? records) false)
12 ((equal? key (caar records)) (car records))
13 (else (assoc key (cdr records)))))
15 (define (insert! key value table)
16 (let ((record (assoc key (cdr table))))
17 (if record
18 (set-cdr! record value)
19 (set-cdr! table
20 (cons (cons key value) (cdr table)))))
21 'ok)
23 (define (make-table)
24 (list '*table*))
26 (define (test-case actual expected)
27 (newline)
28 (display "Actual: ")
29 (display actual)
30 (newline)
31 (display "Expected: ")
32 (display expected)
33 (newline))
35 (define tbl (make-table))
36 ;; 2nd number refers to population in millions
37 (insert! '(usa california los-angeles) 3.88 tbl)
38 (insert! '(usa new-york new-york) 8.41 tbl)
39 (insert! '(china beijing) 21.15 tbl)
40 (insert! '(china shanghai) 24.15 tbl)
41 (insert! '(pakistan karachi) 23.5 tbl)
42 (insert! '(hong-kong) 7.22 tbl)
43 (insert! '(singapore) 5.4 tbl)
44 (test-case (lookup '(usa california los-angeles) tbl) 3.88)
45 (test-case (lookup '(china shanghai) tbl) 24.15)
46 (test-case (lookup '(singapore) tbl) 5.4)
47 (test-case (lookup '(usa california rowland-heights) tbl) #f)
48 (test-case (lookup '(usa new-york) tbl) #f)
49 (test-case (lookup '(usa new-york new-york) tbl) 8.41)
50 (test-case (lookup '(usa new-york new-york new-york) tbl) #f)