2014年6月16日月曜日

開発環境

計算機プログラムの構造と解釈[第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.

コード(BBEdit, Emacs)

sample3_7.scm

#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-

(define (make-account balance password)
  (let ((passwords (list password)))
    (define (withdraw amount passwd)
      (cond ((not (memq passwd passwords))
             "Incorrect password")
            ((>= balance amount)
             (set! balance (- balance amount))
             balance)
            (else "Insufficient funds")))
    (define (deposit amount passwd)
      (if (not (memq passwd passwords))
          "Incorrect password"
          (begin (set! balance (+ balance amount))
                 balance)))
    (define (add-password password new-password)
      (if (not (memq password passwords))
          "Incorrect password"
          (set! passwords (cons new-password passwords))))
    (define (dispatch password m)
      (cond ((eq? m 'withdraw)
             (lambda (amount)
               (withdraw amount password)))
            ((eq? m 'deposit)
             (lambda (amount)
               (deposit amount password)))
            ((eq? m 'add-password)
             (lambda (new-password)
               (add-password password new-password)))
            (else (error "Unknown request -- MAKE-ACCOUNT"
                         m))))
    dispatch))

(define (make-joint account password new-password)
  ((account password 'add-password) new-password)
  account)

;; テスト
(define acc1 (make-account 100 'open-sesame))
(define acc2 (make-joint acc1 'open-sesame 'rosebud))

(print ((acc1 'open-sesame 'withdraw) 40))      ; 60
(print ((acc1 'some-other-password 'deposit) 50)) ; "Incorret password"
(print ((acc2 'rosebud 'deposit) 100))    ; 160
(print ((acc2 'some-other-password 'withdraw) 1000)) ; "Incorret password"
(print ((acc1 'rosebud 'withdraw) 10))               ; 150

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

$ ./sample3_7.scm
60
Incorrect password
160
Incorrect password
150
$

0 コメント:

コメントを投稿