-
Notifications
You must be signed in to change notification settings - Fork 10
/
ex-3.25.scm
88 lines (76 loc) · 2.47 KB
/
ex-3.25.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
;;; 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.
; Let's consider the following interaction:
;
; (define t (make-table))
; (insert! '(a) 'v1)
; (insert! '(a b c) 'v2)
;
; If t was a one-dimensional table, we could assume that each key is paired
; with a value. If t was a two-dimensional table, we could assume that each
; key is paired with a list of records, and the pairs can be treated as
; one-dimensional tables. But t is not. A key might have both a value and
; a subtable, as above.
;
; So that I chose the following represenation:
;
; * Each key is paired with a subtable
; * The car of that subtable points the value for the key
; * The car of each table points #f by default
;
; t
; |
; v
; [o][o]-->[o][/]
; | |
; v v
; #f [o][o]-->[o][o]-->[o][/]
; | | |
; v v v
; a v1 [o][o]-->[o][o]-->[o][/]
; | | |
; v v v
; b #f [o][o]-->[o][/]
; | |
; v v
; c v2
(define (make-table)
(list #f))
(define (lookup keys table)
(define (go keys table)
(if (null? keys)
(car table)
(let ([pair (assoc (car keys) (cdr table))])
(if pair
(go (cdr keys) (cdr pair))
#f))))
(go keys table))
(define (insert! keys value table)
(define (go keys table)
(if (null? keys)
(set-car! table value)
(let ([pair (assoc (car keys) (cdr table))])
(cond
[pair
(go (cdr keys) (cdr pair))]
[else
(let ([subtable (make-table)])
(set-cdr! table (list (cons (car keys) subtable) (cdr table)))
(go (cdr keys) subtable))]))))
(go keys table)
'ok)
(define t (make-table))
#?=t
#?=(lookup '(a) t)
(insert! '(a) 'v1 t)
#?=t
#?=(lookup '(a) t)
#?=(lookup '(a b c) t)
(insert! '(a b c) 'v2 t)
#?=t
#?=(lookup '(a b c) t)
#?=(lookup '(a b) t)
#?=(lookup '(z) t)