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))))
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))))
18 (set-cdr! record value)
20 (cons (cons key value) (cdr table)))))
26 (define (test-case actual expected)
31 (display "Expected: ")
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)