計算機プログラムの構造と解釈[第2版]
(翔泳社)
ハロルド エイブルソン (著) ジュリー サスマン (著)
ジェラルド・ジェイ サスマン (著)
Harold Abelson (原著) Julie Sussman (原著)
Gerald Jay Sussman (原著) 和田 英一 (翻訳)
開発環境
計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の第3章(標準部品化力、オブジェクトおよび状態)、3.3(可変データのモデル化)、3.3.3(表の表現)、局所表の作り方、問題3.25.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
- Scheme手習い
問題3.25.
コード(Emacs)
(begin
(define (print obj)
(display obj)
(newline))
(define (make-table same-key?)
(let ((local-table (list '*table*)))
(define (assoc key records)
(cond ((null? records) #f)
((same-key? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(define (lookup-iter keys table)
(if (null? keys)
#f
(let ((subtable (assoc (car keys) (cdr table))))
(if subtable
(if (null? (cdr keys))
(cdr subtable)
(lookup-iter (cdr keys) subtable))
#f))))
(define (lookup keys) (lookup-iter keys local-table))
(define (insert-record keys value)
(if (null? (cdr keys))
(cons (car keys) value)
(list (car keys)
(insert-record (cdr keys) value))))
(define (insert-iter! keys value table)
(let ((subtable (assoc (car keys) (cdr table))))
(if subtable
(if (null? (cdr keys))
(set-cdr! table value)
(insert-iter! (cdr keys) value subtable))
(set-cdr! table
(cons (insert-record keys value)
(cdr table)))))
'ok)
(define (insert! keys value) (insert-iter! keys value local-table))
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (display "Unknown operation -- TABLE ")
(print m))))
dispatch))
;; 剰余類分解 (同値関係)
(define operation-table (make-table (lambda (a b)
(= (floor-remainder a 2)
(floor-remainder b 2)))))
(define get (operation-table 'lookup-proc))
(define put (operation-table 'insert-proc!))
(print (put '(1 2) 'a))
(print (put '(4 3) 'b))
(print (get '(3 4))) ; a
(print (get '(2 1))) ; b
(print (get '(1 3))) ; #f
(print (get '(4 4))) ; #f
(print (put '(2 4 6 8 10) 'c))
(print (get '(0 10 100 1000 10000))) ; c
)
入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))
$ ./kscheme sample25.scm # kscheme の修正後回し ok error: unbound variable -- a$ $ gosh sample25.scm ok ok a b #f #f ok c $ guile < sample25.scm GNU Guile 2.0.11 Copyright (C) 1995-2014 Free Software Foundation, Inc. Guile comes with ABSOLUTELY NO WARRANTY; for details type `,show w'. This program is free software, and you are welcome to redistribute it under certain conditions; type `,show c' for details. Enter `,help' for help. ok ok a b #f #f ok c scheme@(guile-user)> $
0 コメント:
コメントを投稿