任意の次元のテーブルに一般化する!!
(define (make-table) (let ((local-table (list '*table*))) (define (lookup keys pointer) (let ((record (assoc (car keys) (cdr pointer)))) (if record (if (null? (cdr keys)) (cdr record) (lookup (cdr keys) record)) #f))) (define (insert! keys value pointer) (let ((record (assoc (car keys) (cdr pointer)))) (if record (if (null? (cdr keys)) (ser-cdr! record value) ; overwrite (insert! (cdr keys) value (cdr record))) (if (null? (cdr keys)) (set-cdr! pointer (cons (cons (car keys) value) (cdr pointer))) (let ((new-record (cons (car keys) (cdr pointer)))) (set-cdr! pointer (cons new-record (cdr pointer))) (insert! (cdr keys) value new-record)))))) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) ((eq? m 'local-table) local-table) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define table (make-table)) (define insert! (lambda (keys value) ((table 'insert-proc!) keys value (table 'local-table)))) (define lookup (lambda (keys) ((table 'lookup-proc) keys (table 'local-table))))
(insert! (list 'key-1 'key-2 'key-3) 40) (insert! (list 'key-4 'key-5 'key-6 'key-7) 300) (lookup (list 'key-1 'key-2 'key-3)) ; 40 (lookup (list 'key-4 'key-5 'key-6 'key-7)) ; 300