乐正

Actions speak louder than words.

Sicp-ex3-4

问题

请修改练习3.3中的make-account过程,加上另一个局部状态变量,使得如果一个账户被用不正确的密码连续访问了7次,它就将去调用过程call-the-cops(叫警察)。

解答

练习3.4 (ex3-4.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(define (make-account balance password)
  (let ((counter 0))
    (define (withdraw amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))
    (define (deposit amount)
      (set! balance (+ balance amount))
      balance)
    (define (call-the-cops)
      "Call the cops")
    (define (incorrect-password account)
      (set! counter (+ counter 1))
      (if (>= counter 7)
          (call-the-cops)
          "Inccorect password"))
    (define (dispatch p m)
      (if (eq? p password)
          (cond ((eq? m 'withdraw) withdraw)
                ((eq? m 'deposit) deposit)
                (else (lambda (amount) (error "Unknown request -- MAKE-ACCOUNT" m))))
          incorrect-password))
    dispatch))

测试

1
2
3
4
5
6
7
((acc 'hello 'withdraw) 10)
;Value 13: "Inccorect password"

;;; call repeatly

((acc 'hello 'withdraw) 10)
;Value 20: "Call the cops"

draft

« sicp-ex3-3 sicp-ex3-5 »

Comments