연습문제 3.24 make-table을 same-key? 프로시저를 인자로 받을 수 있게 재설계하기

14 views
Skip to first unread message

xeraph

unread,
Feb 10, 2008, 4:51:27 AM2/10/08
to sicp-sig

; problem 3.24
(define (make-table same-key?)
(let ((local-table (list '*table*)))
(define (assoc key records)
(cond ((null? records) false)
((same-key? key (caar records)) (car records))
(else (assoc key (cdr records)))))

(define (lookup key-1 key-2)
(let ((subtable (assoc key-1 (cdr local-table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(cdr record)
false))
false)))

(define (insert! key-1 key-2 value)
(let ((subtable (assoc key-1 (cdr local-table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(set-cdr! record value)
(set-cdr! subtable
(cons (cons key-2 value)
(cdr subtable)))))
(set-cdr! local-table
(cons (list key-1
(cons key-2 value))
(cdr local-table)))))
'ok)

(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation -- TABLE" m))))

dispatch))

(define t (make-table
(lambda (lhs rhs)
(if (and (number? lhs) (number? rhs))
(< (abs (- lhs rhs)) 1)
(equal? lhs rhs)))))
((t 'insert-proc!) 'math 43.01 'a)
((t 'insert-proc!) 'math 43.02 'b)
((t 'lookup-proc) 'math 43)

결과:
ok
ok
b
>
Reply all
Reply to author
Forward
0 new messages