理系学生日記

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

問題3.4 (3.1.1 Local State Variables)

7回連続でパスワードを間違ったら警察を呼びます!
間違いの回数を数えるためのvalidation-failureとその閾値を保持するvalidation-limitをつくっとく.

(define (call-the-cops)
  (error "call the cops"))

(define (make-account balance password)
  (let ((stored-password password)
	(validation-failure 0)
	(validation-limit 7))
    (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)
	  (begin
	    (set! validation-failure 0)
	    (cond ((eq? m 'withdraw) withdraw)
		  ((eq? m 'deposit) deposit)
		  (else (error "Unknown request -- MAKE-ACCOUNT"
			       m))))
	  (begin
	    (set! validation-failure (+ validation-failure 1))
	    (if (>= validation-failure validation-limit)
		(call-the-cops)
		())
	    (error "Incorrect password: " validation-failure "time(s)"))))
    dispatch))