[英]About "Frames as Repository of Local State"
SICP, 第 3.2.3 节中的练习 3.10 显示以下内容作为先前定义make-withdraw
的替代方法:
(define (make-withdraw initial-amount)
(let ((balance initial-amount))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
并规定我们
使用环境 model 来分析这个
make-withdraw
的替代版本,绘制类似上面的图来说明交互(define W1 (make-withdraw 100)) (W1 50) (define W2 (make-withdraw 100))
)) ) is syntactic sugar for ((lambda ( ) ) )
.然而,在上述请求之前,文本回忆起(let (( )) )
是((lambda ( ) ) )
的语法糖。
现在我猜这个建议意味着我应该分析这个版本的make-withdraw
:
(define (make-withdraw initial-amount)
((lambda (balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
initial-amount))
或者,甚至更好(基于过程定义语法只是底层隐式lambda
表达式的语法糖,来自第 3.2.1 节):
(define make-withdraw
(lambda (initial-amount)
((lambda (balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
initial-amount)))
在这里我看到 3 lambda 程序,而在这个和这个解决方案(非官方;我不知道官方解决方案)中只显示了两个程序。 例如,这是后一种解决方案:
; After (define W1 (make-withdraw 100))
global env
------------------
| |<--- env: global env
| | parameters: initial-amount
| make-withdraw: ----> body:
| | ((lambda (balance)
| | (lambda (amount)
| | (if (>= balance amount)
| | (begin (set! balance (- balance amount))
| | balance)
| | "Insufficient funds"))) initial-amount)
| |
| | E1
| | -----------------------
| |<----| initial-amount: 100 |
| | -----------------------
| | /\
| | E2 |
| | ----------------
| | | balance: 100 |
| | ----------------
| | /\
| | |
| | env: E2
| | parameters: amount
| W1: ---------------> body:
| | (if (>= balance amount)
| | (begin (set! balance (- balance amount))
| | balance)
| | "Insufficient funds")
------------------
而我会想象一个带有parameters: balance
和body: (lambda (amount) …)
也被绘制,因为那是在E2
中运行的(临时?) lambda ( balance
绑定到initial-amount
,而不是100
,这反过来又绑定到E1
中的100
)以生成最终绑定到W1
的过程。
我对么? 如果不是,你能解释一下为什么吗?
当(make-withdraw 100)
被调用时,它会构建一个initial-amount
绑定到100
的环境(这是图中的E1
)。 It then immediately calls another function in this environment : that function constructs a child environment in which balance
is bound to 100
, which is E2
in the diagram, and returns a third function defined in that environment, which is thus the return value of make-withdraw
。
所以W1
现在绑定到第三个 function,其环境是E2
。 构造E2
的第二个 function 已被调用并返回其值(第三个函数):它不再出现在图片中。
这就是它不再存在的原因。
我不确定它是否有帮助,但是如果make-withdraw
根本不存在,考虑一下环境图片可能会很有用,因为它在W1
点的真正虚假噪声已被定义(显然不是在现实生活中,您可能想在其中创建多个帐户:):
(define W1 ((λ (initial-amount)
;; this function was `make-withdraw`
((λ (balance)
;; this function was `let`
(λ (amount)
;; this is what W1 will end up being
(if (>= balance amount)
(begin
(set! balance (- balance amount))
balance)
"Insufficient funds")))
initial-amount))
100))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.