为什么此函数每次都返回不同的值? [英] Why does this function return a different value every time?
问题描述
有人可以解释以下行为吗?具体来说,为什么函数每次都返回不同的列表?为什么每次调用该函数时some-list
都没有初始化为'(0 0 0)
?
Can someone explain the following behavior? Specifically, why does the function return a different list every time? Why isn't some-list
initialized to '(0 0 0)
every time the function is called?
(defun foo ()
(let ((some-list '(0 0 0)))
(incf (car some-list))
some-list))
输出:
> (foo)
(1 0 0)
> (foo)
(2 0 0)
> (foo)
(3 0 0)
> (foo)
(4 0 0)
谢谢!
此外,假设我希望函数每次输出'(1 0 0)
,建议的实现此功能的方法是什么?
Also, what is the recommended way of implementing this function, assuming I want the function to output '(1 0 0)
every time?
推荐答案
'(0 0 0)
是一个文字对象,假定为常量(尽管不受修改).因此,您每次都在有效地修改相同的对象.要在每个函数调用中创建不同的对象,请使用(list 0 0 0)
.
'(0 0 0)
is a literal object, which is assumed to be a constant (albeit not protected from modification). So you're effectively modifying the same object every time. To create different objects at each function call use (list 0 0 0)
.
因此,除非您知道自己在做什么,否则应始终仅将文字列表(如'(0 0 0)
)用作常量.
So unless you know, what you're doing, you should always use literal lists (like '(0 0 0)
) only as constants.
这篇关于为什么此函数每次都返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!