Open Source WEB

##(link2sicp "book-Z-H-22.html#%_thm_3.25" "Exercise 3.25")

解答例

(define (make-table)
  (let ((local-table (list '*table*)))
    (define (lookup key)
      (let ((record (assoc key (cdr local-table))))
        (if record
            (cdr record)
            false)))

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

    (define (print-table) (display local-table) (newline))

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

実行例

gosh> (define operation-table (make-table))
operation-table
gosh> (define get (operation-table 'lookup-proc))
get
gosh> (define put (operation-table 'insert-proc!))
put
gosh> (define print (operation-table 'print-proc))
print
gosh> (put '(1) 1)
ok
gosh> (put '(2) 2)
ok
gosh> (put '(1 1) 11)
ok
gosh> (put '(1 2) 12)
ok
gosh> (put '(2 1) 21)
ok
gosh> (put '(2 2) 22)
ok
gosh> (put '(1 1 1) 111)
ok
gosh> (put '(1 2 2) 122)
ok
gosh> (put '(2 2 2) 222)
ok
gosh> (put '(1 2 3 4) 1234)
ok
gosh> (get '(1))
1
gosh> (get '(5))
#f
gosh> (get '(1 1))
11
gosh> (get '(2 2))
22
gosh> (get '(1 2 3))
#f
gosh> (get '(1 2 3 4))
1234
gosh> (put '(1 2 3 4) 1000)
ok
gosh> (get '(1 2 3 4))
1000

--hidenao

コード

##(sicp-answer-code "ex-3.25.scm")

このサイトは、 IPA の「平成15年度オープンソフトウエア活用基盤整備事業」 の委託事業として開発されたKahuaで試験的に運用しております。

Copyright (c) 2004-2007 株式会社タイムインターメディア About Us