变量的局部状态 [英] Local state of a variable
问题描述
我试图完全理解对象及其变量的局部状态
I am trying to fully understand Objects and local states of their variables
这段代码似乎对多次调用的同一个过程产生了不同的结果,这意味着局部变量发生了变化:
This code seems to produce different results for the same procedure called multiple times, meaning the local variable changes:
(define new-withdraw
(let ((balance 100))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
对于这个其他代码,它产生相同的结果,这意味着它为每个过程调用创建一个新的局部变量:
For this other code, it produces the same result, which means it creates a new local variable for every procedure call:
(define (make-account)
(let ((balance 100))
(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))
我的问题是:
尽管使用 let 创建了局部变量,但为什么它们的行为有所不同?
Why do they behave differently despite creating a local variable using let?
有没有办法让第二个代码像第一个一样工作,而无需将 balance
作为 make-account
的参数传递?
Is there a way one can make the second code work as the first one without passing balance
as a parameter of make-account
?
谢谢
推荐答案
测试代码 1:
> (new-withdraw 0)
100
> (new-withdraw 50)
50
> (new-withdraw 10)
40
测试代码 2:
> (define ac (make-account))
> ((ac 'withdraw) 0)
100
> ((ac 'withdraw) 50)
50
> ((ac 'withdraw) 10)
40
所以两个代码都保持它们的本地状态.代码 1 和代码 2 之间的区别在于代码 1 仅适用于一个帐户,而代码 2 在每次调用时创建一个新帐户" - 对过程的调用返回您需要绑定到变量的调度过程,并且然后如上图使用.
So both codes keep their local state. The difference between code 1 and code 2 is that code 1 works for one account only, whereas code 2 "creates a new account" on each call - the call to the procedure returns the dispatching procedure that you need to bind to a variable, and then use as shown above.
因此你会觉得本地状态丢失了;不是,您可能每次都创建一个新帐户.
Therefore you get the impression that the local state is lost; it's not, you were probably creating a new account every time.
这篇关于变量的局部状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!