gpt4 book ai didi

lisp - Common Lisp 中的本地状态

转载 作者:行者123 更新时间:2023-12-04 18:34:28 27 4
gpt4 key购买 nike

Common Lisp 中的新手问题:

如何让我的程序每次调用都返回具有自己本地绑定(bind)的不同程序对象?目前,我使用 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

我应该以其他方式吗?我的写作方式有问题吗?有人可以帮我解决这个疑问吗?提前致谢。

最佳答案

请注意,即使在 defun 之后-is-global 问题得到了处理,你需要的机器比你需要做的事情要少得多。例如:

(defun make-account (balance)
(lambda (op amount)
(ecase op
((withdraw)
(decf balance amount))
((deposit)
(incf balance amount)))))

(defun account-operation (account op &rest args-to-op)
(apply account op args-to-op))

然后
> (setf joe-acct (make-account 10))
#<Closure 1 subfunction of make-account 4060010B54>

> (setf mary-acct (make-account 100))
#<Closure 1 subfunction of make-account 4060010C94>

> (account-operation joe-acct 'withdraw 10)
0

> (account-operation mary-acct 'deposit 10)
110

显然 account-operation只是一种方便。

关于lisp - Common Lisp 中的本地状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58887691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com