問題3.3、問題3.4 – SICP(計算機プログラムの構造と解釈)その106

問題3.3

(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 (dispatch pass m)
    (if (eq? pass password)
        (cond ((eq? m 'withdraw) withdraw)
              ((eq? m 'deposit) deposit)
              (else (error "Unknown request -- MAKE-ACCOUNT" m)))
        (error "Incorrect Password" pass)))
  dispatch)

(define acc (make-account 100 'hoge))
((acc 'hoge 'withdraw) 40)
gosh> 60
((acc 'hoge 'withdraw) 80)
gosh> "Insufficient funds"
((acc 'hoge 'deposit) 20)
gosh> 80
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
((acc 'fuga 'deposit) 20)
gosh> *** ERROR: Incorrect Password fuga

問題3.4

(define (make-account balance password)
  (let ((failed-access 0))
       (define (withdraw amount)
         (if (>= balance amount)
             (begin (set! balance (- balance amount))
                    balance)
             "Insufficient funds"))
       (define (deposit amount)
         (set! balance (+ balance amount))
         balance)
       (define (dispatch pass m)
         (if (eq? pass password)
             (cond ((eq? m 'withdraw) withdraw)
                   ((eq? m 'deposit) deposit)
                   (else (error "Unknown request -- MAKE-ACCOUNT" m)))
             (begin (set! failed-access (+ failed-access 1))
                    (and (>= failed-access 7) (call-the-cops))
                    (error "Incorrect Password" pass))))
       (define (call-the-cops)
         (display "Call the cops!")
         (newline))
       dispatch))

(define acc (make-account 100 'hoge))
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
((acc 'fuga 'withdraw) 40)
gosh> *** ERROR: Incorrect Password fuga
Call the cops!
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»