2015/11/07

SICP 問題 3.07

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

(define (make-joint account password new-account-password)
  (define (dispatch entered-pass m)
    (if (eq? entered-pass new-account-password)
        (account password m)
        "Incorrect password"))
  dispatch)
gosh> (define peter-acc
  (make-account 100 'open-sesame))
peter-acc
gosh> (define paul-acc
  (make-joint peter-acc 'open-sesame 'rosebud))
paul-acc
gosh> ((paul-acc 'rosebud 'deposit) 30)
130
gosh> ((paul-acc 'rosebud 'withdraw) 50)
80
gosh> ((peter-acc 'open-sesame 'withdraw) 50)
30

意図したように動いてくれてます.
paul-accで 80まで減らしてpeterが50引き出すと残り30ってことは両方のアカウントが同じものを指してるってことですからね.
ただdefineで口座の指定をすると参照先のアカウントのパスワードが間違ってた場合に,make-jointする時点でエラー返したいですよね.
このやりかたじゃそれができないっていうのが気になります.


© 2022 wat-aro