2014年6月13日金曜日

開発環境

計算機プログラムの構造と解釈[第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.1(局所状態変数)、問題 3.4.を解いてみる。

その他参考書籍

問題 3.4.

コード(BBEdit, Emacs)

sample3_4.scm

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

(define (make-account balance password)
  (define count 0)
  (define (call-the-cops) "call the cops")
  (define (withdraw amount passwd)
    (cond ((not (eq? passwd password))
           (set! count (+ count 1))
           (if (= count 7)
               (call-the-cops)
               "Incorrect password"))
          ((>= balance amount)
           (set! balance (- balance amount))
           balance)
          (else "Insufficient funds")))
  (define (deposit amount passwd)
    (if (not (eq? passwd password))
        (begin (set! count (+ count 1))
               (if (= count 7)
                   (call-the-cops)
                   "Incorrect password"))
        (begin (set! balance (+ balance amount))
               balance)))
  (define (dispatch password m)
    (cond ((eq? m 'withdraw)
           (lambda (amount)
             (withdraw amount password)))
          ((eq? m 'deposit)
           (lambda (amount)
             (deposit amount password)))
          (else (error "Unknown request -- MAKE-ACCOUNT"
                       m))))
  dispatch)

;; テスト
(define acc (make-account 100 'secret-password))

(print ((acc 'secret-password 'withdraw) 40))      ; 60
(print ((acc 'some-other-password 'deposit) 50)) ; "Incorret password"
(print ((acc 'secret-password 'deposit) 100))    ; 160
(print ((acc 'some-other-password 'withdraw) 1000)) ; "Incorret password"
(print ((acc 'secret-password 'withdraw) 1000))     ; "Insufficient funds"
(print ((acc 'some-other-password 'withdraw) 1))
(print ((acc 'some-other-password 'withdraw) 1))
(print ((acc 'some-other-password 'deposit) 50))
(print ((acc 'some-other-password 'deposit) 50))
(print ((acc 'some-other-password 'deposit) 50))

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

$ ./sample3_4.scm
60
Incorrect password
160
Incorrect password
Insufficient funds
Incorrect password
Incorrect password
Incorrect password
Incorrect password
call the cops
$

0 コメント:

コメントを投稿