SICP 全笔记

Exercise 3.4. Modify the make-account procedure of exercise 3.3 by adding another local state variable so that, if an account is accessed more than seven consecutive times with an incorrect password, it invokes the procedure call-the-cops.

添加通知警察的机制需要

  1. 另外定义一个过程 call-the-cops
  2. dispatch 需要一个内部变量来记录密码错误的次数
(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 (password-error dummy) "Incorrect password")
  (define (call-the-cops dummy) "Call the Cops!")
  (define dispatch
    (let ((incorrect-pwd 1))
      (lambda (pwd m)
        (if (not (eq? pwd password))
            (begin
              (if (>= incorrect-pwd 7)
                  call-the-cops
                  (begin (set! incorrect-pwd (+ 1 incorrect-pwd))
                         password-error)))
            (begin
              (set! incorrect-pwd 1)
              (cond ((eq? m 'withdraw) withdraw)
                    ((eq? m 'deposit) deposit)
                    (else (error "Unknown request -- MAKE-ACCOUNT"
                                 m))))))))
  dispatch)

(define acc (make-account 100 'secret-password))