灯下 登录
计算机科学 / SICP / 3.2.4 Internal Definitions

Exercise 3.11 · 习题

Exercise 3.11: In 3.2.3 we saw how
the environment model described the behavior of procedures with local state.
Now we have seen how internal definitions work. A typical message-passing
procedure contains both of these aspects. Consider the bank account procedure
of 3.1.1:

(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)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request:
MAKE-ACCOUNT"
m))))
dispatch)

Show the environment structure generated by the sequence of interactions

(define acc (make-account 50))

((acc 'deposit) 40)
90

((acc 'withdraw) 60)
30

Where is the local state for acc kept? Suppose we define another
account

(define acc2 (make-account 100))

How are the local states for the two accounts kept distinct? Which parts of

the environment structure are shared between acc and acc2?

练习 3.11:在 3.2.3 节中,我们看到了环境模型如何描述带有局部状态的过程的行为。现在我们已经了解了内部定义的工作方式。一个典型的消息传递过程同时包含这两个方面。考虑 3.1.1 节中的银行账户过程:

(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)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request:
MAKE-ACCOUNT"
m))))
dispatch)

请画出由以下交互序列生成的环境结构:

(define acc (make-account 50))

((acc 'deposit) 40)
90

((acc 'withdraw) 60)
30

acc 的局部状态保存在哪里?假设我们再定义一个账户

(define acc2 (make-account 100))

两个账户的局部状态是如何相互独立地保存的?acc 和 acc2 之间共享了环境结构的哪些部分?

Racket #lang sicp
(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)
 (define (dispatch m)
 (cond ((eq? m 'withdraw) withdraw)
 ((eq? m 'deposit) deposit)
 (else (error "Unknown request:
 MAKE-ACCOUNT"
 m))))
 dispatch)
Racket #lang sicp
(define acc (make-account 50))

((acc 'deposit) 40)
90

((acc 'withdraw) 60)
30
Racket #lang sicp
(define acc2 (make-account 100))