乐正

Actions speak louder than words.

Sicp-ex3-3

问题

请修改make-account过程,使它能创建一种带密码保护的账户。也就是说,应该让make-account以一个符号作为附加参数,就像:

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

这样产生的账户对象在接到一个请求时,只有同时提供了账户创建时的密码,它才处理这以请求,否则就发出一个抱怨信息:

1
2
3
4
5
((acc 'secret-password 'withdraw) 40)
60

((acc 'other-password 'deposit) 50)
"Incorrect password"

解答

练习3.3 (ex3-3.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(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 (dispatch p m)
    (if (eq? p password)
        (cond ((eq? m 'withdraw) withdraw)
              ((eq? m 'deposit) deposit)
              (else (error "Unknown request -- MAKE-ACCOUNT" m)))
        (lambda (amount) "Incorrect password")))
  dispatch)

测试

1
2
3
4
5
6
7
8
9
10
11
(define acc (make-account 100 'secret))
;Value: acc

((acc 'secret 'withdraw) 10)
;Value: 90

((acc 'secret 'deposit) 100)
;Value: 190

((acc 'hello 'withdraw) 100)
;Value 18: "Incorrect password"

draft

« sicp-ex3-2 sicp-ex3-4 »

Comments