【发布时间】:2012-04-19 02:41:02
【问题描述】:
我必须反转一个简单(一维)列表的元素。我知道有一个内置的反向功能,但我不能用它来做这个。
这是我的尝试:
(defun LISTREVERSE (LISTR)
(cond
((< (length LISTR) 2) LISTR) ; listr is 1 atom or smaller
(t (cons (LISTREVERSE (cdr LISTR)) (car LISTR))) ; move first to the end
)
)
输出非常接近,但是是错误的。
[88]> (LISTREVERSE '(0 1 2 3))
((((3) . 2) . 1) . 0)
所以我尝试使用append 而不是cons:
(t (append (LISTREVERSE (cdr LISTR)) (car LISTR)))
但是得到了这个错误:
*** - APPEND: A proper list must not end with 2
有什么帮助吗?
【问题讨论】:
-
使用 LENGTH 不是一个好主意。它破坏了链接 cons 单元列表的目的。 LENGTH 遍历整个列表以确定长度。
-
APPEND 错误有点神秘,但表示最后的参数不是列表,而是数字 2。
-
除非我弄错了,你的
append版本应该可以工作,只要你将最后一个参数放入列表中。
标签: lisp common-lisp clisp