3

我正在 Lisp 中做一些功课,使用 clisp 进行测试,我正在加载此代码并在 clisp 中运行

(defun myreverse (thelist)

(reverse thelist)
(print thelist)

(if (equal thelist nil)
    nil
    (if (consp (first thelist))
            (cons (myreverse (reverse (first thelist))) 
                (myreverse (reverse (rest thelist))))
            (cons (first thelist) (myreverse (rest thelist))))))

我对 Lisp 有点陌生,但是这段代码根本没有反转thelist,我的输出是:

[18]> (myreverse '(a (b c) d))

(A (B C) D)
((B C) D)
(C B)
(B)
NIL
(D)
NIL
(A (C B) D)

我的代码的第一行说(reverse thelist),为什么它不反转第一个打印语句?我错过了什么吗?

4

1 回答 1

4

我相信(reverse)它没有副作用,因此它不会反转原始列表,而是返回一个新的、反转的列表。这在 Common Lisp 中并不那么自然,但在 Scheme 中却是意料之中的。不过,这里是文档http://www.lispworks.com/documentation/HyperSpec/Body/f_revers.htm#reverse

我想你想要的是(nreverse).

于 2012-01-11T05:19:14.590 回答