SICP_3.3-3.4

 1 ;;;;;;;;;;3.3
 2 (define (make-account balance secret-password)
 3   
 4         (define (withdraw amount)
 5         (if (>= balance amount)
 6             (begin (set! balance (- balance amount))
 7                    balance)
 8             "Insufficient funds"))
 9   
10              (define (deposit amount)
11                (set! balance (+ balance amount))
12                balance)
13   
14              (define (dispatch m)
15                (cond 
16                      ((eq? m 'withdraw) withdraw)
17                      ((eq? m 'deposit) deposit)
18                      (else (error "Unknow request -- MAKE-ACCOUNT"
19                                   m))))
20   (lambda (p m)
21     (if (eq? p secret-password) (dispatch m)
22         (lambda (x) "Incorrect password"))))
23 
24 
25 ;(define acc (make-account 100 'secret-password))
26 ;((acc 'secret-password 'withdraw) 40)
27 ;((acc 'some-other-password 'deposit) 50)
28 
29 ;;;;;;;;3.4
30 (define (new-make-account balance secret-password)
31   (let ((count 0))
32     
33     (define (withdraw amount)
34       (if (>= balance amount)
35           (begin (set! balance (- balance amount))
36                  balance)
37           "Insufficient funds"))
38 
39     (define (deposit amount)
40       (set! balance (+ balance amount))
41       balance)
42 
43     (define (dispatch m)
44       (cond ((eq? m 'withdraw) withdraw)
45             ((eq? m 'deposit) deposit)
46             (else (error "Unkonw request --MAKE-ACCOUNT"
47                          m))))
48 
49     (define (call-the-cops x)
50       "Call the cops")
51 
52     (define (select p m)
53       (cond ((eq? p secret-password) (dispatch m))
54             (else (lambda (x)
55                     (if (>= count 7)
56                         (call-the-cops x)
57                         (begin (set! count (+ count 1))
58                               "Incorrect password"))))))
59     select))
60 
61 (define acc (new-make-account 100 'secret-password))
62 ((acc 'secret-password 'withdraw) 40)
63 
64 (define (many-false-withdraw num)
65   (if (< num 7)
66       (begin
67         ((acc 'other-password 'withdraw) 40)
68         (set! num (+ num 1))
69         (many-false-withdraw num))
70       ((acc 'other-password 'withdraw) 40)))
71 
72 (many-false-withdraw 0)

 

3.4最好还加个登录后清零的函数

posted @ 2017-03-09 15:41  lan126  阅读(224)  评论(0编辑  收藏  举报