乐正

Actions speak louder than words.

Sicp-ex3-7

问题

考虑如练习3.3所描述的,由make-account创建的带有密码的银行账户对象。假定我们的银行系统中需要一种提供公用账户的能力。请定义过程make-joint创建这种账户。make-join应该有三个参数:第一个是有密码保护的账户;第二个参数是一个密码,它必须与那个已经定义的密码匹配,以使make-joint操作能够继续下去;第三个参数是新密码。make-joint用这一新密码创建起对那个原来账户的另一访问途径。 例如,如果peter-acc是一个具有密码的open-sesame的银行账户,那么

1
2
(define paul-acc
  (make-joint petter-acc 'open-sesame 'rosebud))

将使我们可以通过名字paul-acc和密码rosebud对账户peter-acc做现金交易。你可能希望修改自己对练习3.3的解,加入这一新功能。

解答

练习3.7 (ex3-7.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
(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)

(define (make-joint account password new-password)
  (define (dispatch p m)
    (if (eq? p new-password)
        (account password m)
        (lambda (amount) "Incorrect password")))
  dispatch)

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(define peter-acc (make-account 100 'open-sesame))
;Value: peter-acc

(define paul-acc (make-joint peter-acc 'open-sesame 'rosebud))
;Value: paul-acc

((paul-acc 'rosebud 'deposit) 100)
;Value: 200

((peter-acc 'open-sesame 'withdraw) 150)
;Value: 50

((paul-acc 'rose 'deposit) 100)
;Incorrect password

draft

« sicp-ex3-6 sicp-ex3-8 »

Comments