Scheme 变量的局部状态
我试图完全理解对象及其变量的局部状态 对于多次调用的相同过程,此代码似乎会产生不同的结果,这意味着局部变量会发生变化:Scheme 变量的局部状态,scheme,racket,let,object-state,Scheme,Racket,Let,Object State,我试图完全理解对象及其变量的局部状态 对于多次调用的相同过程,此代码似乎会产生不同的结果,这意味着局部变量会发生变化: (define new-withdraw (let ((balance 100)) (lambda (amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insu
(define new-withdraw
(let ((balance 100))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
对于其他代码,它会产生相同的结果,这意味着它会为每个过程调用创建一个新的局部变量:
(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创建局部变量,它们的行为却不同
- 是否有一种方法可以使第二个代码与第一个代码一样工作,而不将
作为余额
的参数传递生成帐户
> (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在每次调用时“创建一个新帐户”-对过程的调用返回需要绑定到变量的调度过程,然后如上所示使用
因此,你得到的印象是,地方政府已经迷失;不是,你可能每次都在创建一个新帐户。Ha,我明白了。当我测试程序时,我运行
(define acc make account)(((acc)'draw)50)
,以便每次使用acc
时都定义一个新的局部变量