【问题标题】:Lisp isn't reversing my listsLisp 没有反转我的列表
【发布时间】:2012-02-07 12:38:17
【问题描述】:

我在 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),为什么第一条打印语句不反转?我错过了什么吗?

【问题讨论】:

  • (null thelist) 在 Common Lisp 中比 (equal thelist nil) 更惯用。

标签: common-lisp reverse clisp


【解决方案1】:

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

我想你想要的是(nreverse)

【讨论】:

  • 啊,好吧,所以它反转了 (B C) 因为当它返回列表时,它实际上去了代码中的其他地方(即 - 全部反转)?
  • 是的,它只是打印thelist,在这种情况下恰好是(reverse (first thelist)) 的结果
  • 太棒了,非常感谢,我真的很困惑。
  • 所以无论如何,你想要的是,在开始时,而不是 (reverse thelist) 之类的 (nreverse thelist)
  • 我认为值得注意的是,即使对于像(nreverse thelist) 这样修改列表的函数,您也必须使用返回值(例如(let ((x (list 1 2 3))) (setf x (nreverse x))))。
猜你喜欢
  • 2020-12-18
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
相关资源
最近更新 更多