乐正

Actions speak louder than words.

Sicp-ex3-41

问题

Ben Bitdiddle 觉得像下面这样实现银行账户可能更好(其中带注释的行修改了):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(define (make-account balance)
  (define (withdraw amount)
    (if (>= balance amount)
      (begin (set! balance (- balance amount))
             balance)
      "Insufficient funds"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (let ((protected (make-serializer)))
    (define (dispatch m)
      (cond ((eq? m 'withdraw) (protected withdraw))
            ((eq? m 'deposit) (protected deposit))
            ((eq? m 'balance) ((protected (lambda () balance)))) ; serialized
            (else (error "Unknown request -- MAKE-ACCOUNT" m))))
    dispatch))

因为允许非串行化地访问银行账户可能导致不正常的行为。你同意 Ben 的观点吗?是否存在某种情况,能证明 Ben 所担心的问题?

解答

非串行化地访问银行账户可能产生余额显示不正确。

draft

« sicp-ex3-40 sicp-ex3-42 »

Comments