【发布时间】:2020-03-12 05:40:32
【问题描述】:
Common Lisp 中的新手问题:
如何让我的过程在每次调用时返回具有自己本地绑定的不同过程对象?目前,我使用 let 创建本地状态,但是两个函数调用共享相同的本地状态。这是代码,
(defun make-acc ()
(let ((balance 100))
(defun withdraw (amount)
(setf balance (- balance amount))
(print balance))
(defun deposit (amount)
(setf balance (+ balance amount))
(print balance))
(lambda (m)
(cond ((equal m 'withdraw)
(lambda (x) (withdraw x)))
((equal m 'deposit)
(lambda (x) (deposit x)))))))
;; test
(setf peter-acc (make-acc))
(setf paul-acc (make-acc))
(funcall (funcall peter-acc 'withdraw) 10)
;; Give 90
(funcall (funcall paul-acc 'withdraw) 10)
;; Expect 90 but give 80
我应该用其他方式吗?我的写作方式有问题吗?有人可以帮我解决这个疑问吗?提前致谢。
【问题讨论】:
-
请注意,Common Lisp 有一个对象系统,因此通常不需要通过 lambda 对状态进行建模。
标签: lisp common-lisp state let