2015年9月30日水曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の第3章(標準部品化力、オブジェクトおよび状態)、3.1(代入と局所状態)、3.1.3(代入を取り入れた代価)、問題3.7.を解いてみる。

その他参考書籍

問題3.7.

コード(Emacs)

(begin
  (define print (lambda (x) (display x) (newline)))

  (define (make-account balance password)
    (define (withdraw amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))
    (define (deposit amount)
      (set! balance (+ balance amount))
      balance)
    (define (make-joint pwd)
      (lambda (password m)
        (if (eq? pwd password)
            (cond ((eq? m (quote withdraw)) withdraw)
                  ((eq? m (quote deposit)) deposit)
                  ((eq? m (quote make-joint)) make-joint)
                  (else ((lambda ()
                           (display "Unknown request -- MAKE-JOINT ")
                           (print m)))))
            (lambda (x) "Incorrect password"))))
    (define (dispatch pwd m)
      (if (eq? pwd password)
          (cond ((eq? m (quote withdraw)) withdraw)
                ((eq? m (quote deposit)) deposit)
                ((eq? m (quote make-joint)) make-joint)
                (else (lambda ()
                        (display "Unknown request -- MAKE-ACCOUNT ")
                        (print m))))
          (lambda (x) "Incorrect password")))
    dispatch)

  (define (make-joint account password new-password)
    ((account password (quote make-joint)) new-password))

  (define peter-acc (make-account 100 (quote open-sesame)))
  (define paul-acc (make-joint peter-acc (quote open-sesame) (quote rosebud)))

  (print ((peter-acc (quote open-sesame) (quote withdraw)) 50))
  (print ((paul-acc (quote rosebud) (quote withdraw)) 10))
  (print ((peter-acc (quote rosebud) (quote withdraw)) 10))
  (print ((paul-acc (quote open-sesame) (quote withdraw)) 10))
  (print ((peter-acc (quote open-sesame) (quote deposit)) 100))
  (print ((paul-acc (quote rosebud) (quote deposit)) 50)))

入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))

$ ./kscheme sample7.scm
50
40
Incorrect password
Incorrect password
140
190
$

0 コメント:

コメントを投稿

Comments on Google+: