-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.sld
52 lines (47 loc) · 1.41 KB
/
table.sld
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
(define-library (table)
(export <table>
table
table-find-pair
table-has-key?
table-keys
table-ref)
(import (scheme base)
(srfi 1))
(begin
; simple association table / dictionary
; O(n) lookup
;
; (table <key-eq> ((<key>) <value>) ...)
; (table ((<key>) <value>) ...)
; key-eq is a function that takes two keys and returns #t if they are equal
;
; Example usage
; (table () (('a) 12)
; (('b) 34))
; Usage with string keys:
; (table (string=?) (("X") 100)
; (("Y") 200))
(define-syntax table
(syntax-rules ()
((_ () ((a) b) ...)
(let ((data (list (cons a b) ...)))
(table-record data eqv?)))
((_ (key-eq) ((a) b) ...)
(let ((data (list (cons a b) ...)))
(table-record data key-eq)))))
(define-record-type <table>
(table-record key-values key-eq)
table?
(key-values table-key-values)
(key-eq table-key-eq))
(define (table-ref t k)
(let ((pair (table-find-pair t k)))
(if pair
(cdr pair)
(error "table-ref: no such key" k))))
(define (table-has-key? t k)
(not (eqv? #f (table-find-pair t k))))
(define (table-find-pair t k)
(assoc k (table-key-values t) (table-key-eq t)))
(define (table-keys t)
(map car (table-key-values t)))))