gpt4 book ai didi

Lisp - 附加到列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:46 25 4
gpt4 key购买 nike

我是 lisp 的新手。我没有正确理解如何在列表上实现附加功能。我尝试了以下程序。

(defvar temp)
(setq temp '())
(append temp (logxor 1 0))

temp 似乎只存储了 NIL 值,而它应该在其中存储 1。

最佳答案

append返回新值,它不修改其参数。您需要使用 setq :

(setq temp (append temp (list 1)))

push (添加到列表的开头,而不是结尾!):

(push 1 temp)

您还可以使用 nconc用于破坏性附加,但您仍然需要setq因为你不能破坏性地附加到 nil:

(defparameter temp nil)
(append temp '(1))
;; returns (1) but `temp` is still empty
(nconc temp '(1))
;; also returns (1) but `temp` is still empty
(setq temp (append temp (list 2)))
;; now temp is (2)
(append temp '(1))
;; returns (2 1) but `temp` is still (2)
(nconc temp '(1))
;; returns (2 1) and `temp` is now (2 1)

请注意,当您计划使用 nconc 破坏性地附加到它们时,不应使用引号列表(如 '(1)) , 请参阅 Why does an elisp local variable keep its value in this case?了解更多信息和链接,尤其是 Issue CONSTANT-MODIFICATION .

关于Lisp - 附加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28928344/

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