【发布时间】:2014-12-29 02:05:36
【问题描述】:
我正在尝试完全理解对象及其变量的局部状态
这段代码似乎对多次调用的同一过程产生了不同的结果,这意味着局部变量发生了变化:
(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 创建了局部变量,但它们的行为却不同?
有没有一种方法可以使第二个代码像第一个代码一样工作,而无需将
balance作为make-account的参数传递?
谢谢
【问题讨论】:
标签: scheme racket let object-state