Push 不会将列表修改为函数参数会将、函数、参数、列表

由网友(疼心的不过是你的折磨丶)分享简介:我是 common lisp 的新手,所以希望有人能向我澄清这一点:I'm new to common lisp, so hope someone would clarify this to me:假设我们有一个列表,想用 push 添加一个项目来修改它:say we have a list and want t...

我是 common lisp 的新手,所以希望有人能向我澄清这一点:

I'm new to common lisp, so hope someone would clarify this to me:

假设我们有一个列表,想用 push 添加一个项目来修改它:

say we have a list and want to add an item with push to modify it:

CL-USER> (defparameter xx '(1 2 3))
XX
CL-USER> xx
(1 2 3)
CL-USER> (push 100 xx)
(100 1 2 3)
CL-USER> xx
(100 1 2 3)

正如预期的那样.但是当我尝试对函数执行相同操作时,它不会修改列表:

as expected. But when i try to do the same with the function, it doesn't modify a list:

CL-USER> (defun push-200 (my-list)
           (push 200 my-list))
PUSH-200
CL-USER> (push-200 xx)
(200 100 1 2 3)
CL-USER> xx
(100 1 2 3)

所以我尝试像这样比较参数和我的列表:

so i tried to compare argument and my list like this:

CL-USER> (defun push-200 (my-list)
           (format t "~a" (eq my-list xx))
           (push 200 my-list))

WARNING: redefining COMMON-LISP-USER::PUSH-200 in DEFUN
PUSH-200
CL-USER> (push-200 xx)
T
(200 100 1 2 3)
CL-USER> xx
(100 1 2 3)

它说对象是相同的.所以问题是:我在这里忽略了什么?

it says the objects are identical. So the question is: what was the thing I've overlooked here?

推荐答案

(defun push-200 (my-list)
  (push 200 my-list))

这会修改变量my-list.该变量现在指向一个新的cons.

This modifies the variable my-list. The variable now points to a new cons.

基本上是:(setq my-list (cons 200 my-list).

(push-200 xx)

Common Lisp 将 xx 评估为一个值并将列表传递给 push-200.xx 不是传递的,而是它的值.因此,Lisp 系统无法修改 xx 以指向不同的 cons,因为它没有通过.

Common Lisp evaluates xx to a value and passes the list to push-200. xx is not passed, but the value of it. So, the Lisp system can't modify xx to point to a different cons, since it is not passed.

阅读全文

相关推荐

最新文章