開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: MIT/GNU Scheme
計算機プログラムの構造と解釈(Gerald Jay Sussman(原著)、Julie Sussman(原著)、Harold Abelson(原著)、和田 英一(翻訳)、ピアソンエデュケーション、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の3(標準部品化力, オブジェクトおよび状態)、3.1(代入と局所状態)、3.1.3(代入を取り入れた代価)、同一と変化、命令型プログラムの落とし穴の問題 3.7、3.8を解いてみる。
その他参考書籍
問題 3.7
コード(BBEdit)
sample.scm
(define (make-account balance secret-password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch password m) (if (eq? secret-password password) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unkown request -- MAKE-ACCOUNT" m))) (lambda (a) "Incorrect password"))) dispatch) (define (make-joint acc secret-password joint-password) (define (dispatch password m) (if (eq? password joint-password) (acc secret-password m) (lambda (a) "Incorrect password"))) dispatch) (define peter-acc (make-account 100 'open-sesame)) (define paul-acc (make-joint peter-acc 'open-sesame 'rosebud))
入出力結果(Terminal, REPL(Read, Eval, Print, Loop))
1 ]=> ((peter-acc 'open-sesame 'withdraw) 10) ;Value: 90 1 ]=> ((paul-acc 'rosebud 'withdraw) 20) ;Value: 70 1 ]=> ((peter-acc 'open-sesame 'deposit) 30) ;Value: 100 1 ]=> ((paul-acc 'rosebud 'deposit) 40) ;Value: 140
問題文中にあった、「問題 3.3の解答を修正する」必要がなかったけど、これでいいのかなぁ。
問題 3.8
左から右へ評価。
コード(BBEdit)
sample.scm
(define f (let ((a 1)) (lambda (x) (set! a (* a x)) a))) (define left (f 0)) (define right (f 1))
入出力結果(Terminal, REPL(Read, Eval, Print, Loop))
1 ]=> (+ left right) ;Value: 0
右から左へ評価。
コード(BBEdit)
sample.scm
(define f (let ((a 1)) (lambda (x) (set! a (* a x)) a))) (define right (f 1)) (define left (f 0))
入出力結果(Terminal, REPL(Read, Eval, Print, Loop))
1 ]=> (+ left right) ;Value: 1
0 コメント:
コメントを投稿