LISP:反转点列表

LISP: Reversing a dotted list

Common Lisp:简要介绍中有一个问题。问题是获取列表中的 last 元素而不是 cons cell。宏 LAST returns cons cell 在虚线列表中。提出的问题是使用宏 reverse 而不是 last,但是 clispsbcl 都抛出错误。

(reverse '(a b c . d))
=> error

CLHS 文档说我们只能反转一个适当的列表(序列)而不是点列表或循环列表。

编辑

我用LAST写了程序。

(defun last-element (x)
 "x is a list with last element as dotted pair"
  (cdr (last x)))

我不知道在这种情况下如何使用reverse

函数 last return 是任何适当列表或虚线列表的最后 cons 单元格,只要列表不是循环的。

听起来问题是关于练习 6.6:

Use the LAST function to write a function called LAST-ELEMENT that returns the last element of a list instead of the last cons cell. Write another version of LAST-ELEMENT using REVERSE instead of LAST. Write another version using NTH and LENGTH.

如果有意的话,练习将指定点列表输入。 When list is used in an unqualified way, it almost always means proper list。对于正确的列表 last 将 return 一个 cons 单元格 nilcdr 中,例如 (last '(a b c d) --> (d . nil),或者只是 (d),因此正确列表的最后一个元素是最后一个 cons 单元格的 car

如果您想同时处理正确列表和虚线列表,您需要确定输入是哪个并相应地处理它:对于虚线列表,最后一个“元素”将是最后一个 cdr cons单元格。相应地处理 reverse 版本的输入意味着您必须在应用 reverse 之前确定输入是正确的列表还是虚线列表。在使用 reverse.

之前,您可以编写一个函数将虚线列表转换为正确的列表

从技术上讲,the Standard does not consider the atom which terminates a dotted list to be one of its elements

element n. 1. (of a list) an object that is the car of one of the conses that comprise the list.

对于像 (a b c d) 这样的适当列表,nil 是终止原子(因为 (a b c d) 等同于 (a b c d . nil)),而 (d . nil) 是最后的缺点; d 是最后一个 conscar,因此是列表的最后一个元素。对于像 (a b c . d) 这样的点列表,d 是终止原子,(c . d) 是最后一个 cons。由于 c 是最后一个 conscarc 是最后一个真实的 元素 ,在标准定义的意义上, 虚线列表。更准确地说 d(a b c . d) 的最后一个 成员

但是,Common Lisp:简要介绍 中的练习 6.6 仅适用于适当的列表。