Exercise 3.10: In the make-withdraw
procedure, the local variable balance is created as a parameter of
make-withdraw. We could also create the local state variable
explicitly, using let, as follows:
(define (make-withdraw initial-amount)
(let ((balance initial-amount))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance
(- balance amount))
balance)
"Insufficient funds"))))
Recall from 1.3.2 that let is simply syntactic sugar for a
procedure call:
(let ((⟨var⟩ ⟨exp⟩)) ⟨body⟩)
is interpreted as an alternate syntax for
((lambda (⟨var⟩) ⟨body⟩) ⟨exp⟩)
Use the environment model to analyze this alternate version of
make-withdraw, drawing figures like the ones above to illustrate the
interactions
(define W1 (make-withdraw 100))
(W1 50)
(define W2 (make-withdraw 100))
Show that the two versions of make-withdraw create objects with the same
behavior. How do the environment structures differ for the two versions?
练习 3.10:在 make-withdraw 过程中,局部变量 balance 作为 make-withdraw 的参数被创建。我们也可以用 let 来显式创建局部状态变量,如下所示:
(define (make-withdraw initial-amount)
(let ((balance initial-amount))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance
(- balance amount))
balance)
"Insufficient funds"))))
回忆 1.3.2 节,let 不过是过程调用的语法糖:
(let ((⟨var⟩ ⟨exp⟩)) ⟨body⟩)
被解释为以下形式的另一种语法:
((lambda (⟨var⟩) ⟨body⟩) ⟨exp⟩)
用环境模型来分析这个 make-withdraw 的另一种版本,绘制类似上面的图示来说明以下交互:
(define W1 (make-withdraw 100))
(W1 50)
(define W2 (make-withdraw 100))
证明两个版本的 make-withdraw 创建了具有相同行为的对象。两个版本的环境结构有何不同?
(define (make-withdraw initial-amount)
(let ((balance initial-amount))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance
(- balance amount))
balance)
"Insufficient funds")))) (let ((⟨var⟩ ⟨exp⟩)) ⟨body⟩) ((lambda (⟨var⟩) ⟨body⟩) ⟨exp⟩) (define W1 (make-withdraw 100))
(W1 50)
(define W2 (make-withdraw 100))