Push 不会修改作为函数参数的列表 [英] Push doesn't modify the list being a function argument

查看:28
本文介绍了Push 不会修改作为函数参数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是普通 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.

这篇关于Push 不会修改作为函数参数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆