Skip to content

Commit 027781e

Browse files
committed
Add the implementation of 1d and 2d table
1 parent e9778e2 commit 027781e

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

chapter3/1d-table.rkt

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#lang racket
2+
3+
(define (make-table)
4+
(mcons '*table* '()))
5+
6+
(define (assoc key records)
7+
(cond ((null? records) false)
8+
((equal? key (mcar (mcar records)))
9+
(mcar records))
10+
(else (assoc key (mcdr records)))))
11+
12+
;;; O(N)
13+
(define (lookup key table)
14+
(let ((record (assoc key (mcdr table))))
15+
(if record
16+
(mcdr record)
17+
false)))
18+
19+
(define (insert! key value table)
20+
(let ((record (assoc key (mcdr table))))
21+
(if record
22+
(set-mcdr! record value)
23+
(set-mcdr! table (mcons (mcons key value) (mcdr table)))))
24+
'ok)
25+
26+
(module+ test
27+
(require rackunit)
28+
29+
(test-case "Test for 1 dimensional table"
30+
(define 1dt (make-table))
31+
(check-false (lookup 'no-exist-key 1dt))
32+
(insert! 'name 'Jon 1dt)
33+
(check-equal? (lookup 'name 1dt) 'Jon)
34+
)
35+
)
36+
(provide make-table insert! lookup assoc)

chapter3/2d-table.rkt

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#lang racket
2+
(require "1d-table.rkt")
3+
4+
(define (make-table)
5+
(let ((local-table (mcons '*table* '())))
6+
(define (lookup key-1 key-2)
7+
(let ((subtable (assoc key-1 (mcdr local-table))))
8+
(if subtable
9+
(let ((record (assoc key-2 (mcdr subtable))))
10+
(if record
11+
(mcdr record)
12+
false))
13+
false)))
14+
15+
(define (insert! key-1 key-2 value)
16+
(let ((subtable (assoc key-1 (mcdr local-table))))
17+
(if subtable
18+
(let ((record (assoc key-2 (mcdr subtable))))
19+
(if record
20+
(set-mcdr! record value)
21+
(set-mcdr! subtable (mcons (mcons key-2 value)
22+
(mcdr subtable)))))
23+
(set-mcdr! local-table (mcons
24+
(mcons key-1
25+
(mcons (mcons key-2 value) '()))
26+
(mcdr local-table)))))
27+
'ok)
28+
(define (dispatch m)
29+
(cond ((eq? m 'lookup-proc) lookup)
30+
((eq? m 'insert-proc!) insert!)
31+
(else (error "Unknown Operation -- TABLE" m))))
32+
dispatch))
33+
34+
35+
(module+ test
36+
(require rackunit)
37+
38+
(test-case "Test for 2d table"
39+
(define operation-table (make-table))
40+
(define get (operation-table 'lookup-proc))
41+
(define put (operation-table 'insert-proc!))
42+
(check-false (get 'math '+))
43+
(put 'math '+ 43)
44+
(check-false (get 'math '*))
45+
(check-equal? (get 'math '+) 43)
46+
)
47+
)

0 commit comments

Comments
 (0)