gpt4 book ai didi

list - 构建带有非列表尾部的列表有什么意义?

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

Emacs lisp manual关于函数 nconc 的声明:

Since the last argument of nconc is not itself modified, it is reasonable to use a constant list, such as '(4 5), as in the above example. For the same reason, the last argument need not be a list

我确实会写

(setq x '(1 2 3))
=> (1 2 3)

(nconc x 0)
=> (1 2 3 . 0)

但这会产生一个完全损坏的列表:

(length x)
=> eval: Wrong type argument: listp, 0

(butlast x)
=> butlast: Wrong type argument: listp, 0
  • 如何检索原始列表? (reverse (cdr (reverse '(1 2 3 . 0)))) 也没有削减它。
  • 这种模式在哪些情况下有用?在标准发行版中,minibuffer.el 中的一些函数使用它,特别是 completion-all-completions 等。

最佳答案

它们不是“损坏的”列表;它们实际上被称为不正确 列表(与以nil 结尾的列表相反,后者是正确 列表)。许多列表函数,例如您刚刚命名的 lengthbutlast,需要正确的列表,而 listp 仅针对正确的列表返回 true。

不正确的列表用于关联列表(其中关联通常不正确;尽管列表本身必须正确)。


如果你想把一个不正确的列表变成正确的,你有两个选择:

  • 删除“不当”元素。
  • 将不正确的元素视为正确列表的最后一个元素。

这是我编写的名为 properise 的过程,它将执行前者:

(defun properise (x)
(let ((r nil))
(while (consp x)
(push (pop x) r))
(nreverse r)))

(如果您想要后一种行为,请在 nreverse 行之前添加 (unless (null x) (push x r))。)

关于list - 构建带有非列表尾部的列表有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573506/

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