我在修改关联列表的条目时遇到了问题。当我运行这段代码时
示例A
(set 'Dict '(("foo" "bar")))
(letn (key "foo"
entry (assoc key Dict))
(setf (assoc key Dict) (list key "new value")))
(println Dict)结果是:
(("foo" "new value")) ; OK这是意料之中的。用这个代码
示例B
(set 'Dict '(("foo" "bar")))
(letn (key "foo"
entry (assoc key Dict))
(setf entry (list key "new value"))) ; the only change is here
(println Dict)结果是:
(("foo" "bar")) ; huh?为什么在第二种情况下没有更新Dict?
编辑
我想要的是检查条目是否在Dict中,如果是的话--更新它,否则就别管它了。使用letn,我希望避免重复的代码
(letn (key "foo"
entry (assoc key Dict))
(if entry ; update only if the entry is there
(setf entry (list key "new value")))发布于 2012-11-15 14:04:04
在letn表达式中,变量条目包含关联的副本,而不是引用。直接设置关联,如Cormullion的示例所示:
(setf (assoc key Dict) (list key "new value"))在newLISP编程模型中,一切都只能引用一次。作业总是复制一份。
发布于 2012-11-15 13:20:06
我对协会名单的理解是,它们是这样工作的:
> (set 'data '((apples 123) (bananas 123 45) (pears 7)))
((apples 123) (bananas 123 45) (pears 7))
> (assoc 'pears data)
(pears 7)
> (setf (assoc 'pears data) '(pears 8))
(pears 8)
> data
((apples 123) (bananas 123 45) (pears 8))
> (assoc 'pears data)
(pears 8)
>如果要检查键是否存在并更新其值,请执行以下操作:
(letn (key "foo")
(if (lookup key Dict)
(setf (assoc key Dict) (list key "new value"))))https://stackoverflow.com/questions/13397316
复制相似问题