理系学生日記

おまえはいつまで学生気分なのか

問題3.3 (3.1.1 Local State Variables)

パスワードつきの銀行口座作るよ!
この銀行口座は,振込と引き出しができるんですけど,パスワードがあってないとそういうのができないスゴい口座だ!

(define (make-account balance password)
  (let ((stored-password 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 password m)
      (if (eq? stored-password password)
	  (cond ((eq? m 'withdraw) withdraw)
		((eq? m 'deposit) deposit)
		(else (error "Unknown request -- MAKE-ACCOUNT"
			     m)))
	  (error "Incorrect password")))
    dispatch))
(define acc (make-account 100 'secret-password))
((acc 'secret-password 'withdraw) 40)    ; 60
((acc 'some-other-password 'deposit) 50) ; "*** ERROR: Incorrect password"