【问题标题】:How to make deep-reverse function in Lisp如何在 Lisp 中制作深度反向函数
【发布时间】:2016-10-08 09:37:28
【问题描述】:

我正在尝试在 lisp 中创建深度反向函数。例如:

(a (b c d) e) -> (e (d c b) a)    

这是我的代码。

(defun deeprev (l)
  (cond ((null l) nil)
        ((list (car l)) (append (deeprev (cdr l)) (deeprev (car l))))
        (t (append (deeprev (cdr l))(car l)))
  )
)

每当我编译和加载时,我都会出错:

Error: Attempt to take the car that is not listp

【问题讨论】:

标签: recursion lisp common-lisp reverse


【解决方案1】:

最简单的选择是只使用REVERSE 当前列表,并使用MAPCAR 反转所有具有相同功能的子列表。

(defun tree-reverse (tree)
  "Deep reverse TREE if it's a list. If it's an atom, return as is."
  (if (listp tree)
      (mapcar #'tree-reverse
              (reverse tree))
      tree))

(tree-reverse '(a (b c d) e)) ;=> (E (D C B) A)

【讨论】:

    【解决方案2】:

    在您的函数中,您假设如果l 输入变量不是nil,那么它必然是一个cons-cell,因为您在(list ...) 函数中无条件地采用(car l)。这就是你有错误的原因。还有很多其他不是nil 的东西此时可以绑定到l,比如数字或符号。

    顺便说一句,(list ...) 只是建立一个列表,你需要使用listp 来代替。由于您排除了nil 的情况,并且列表定义为nilcons,因此您也可以使用consp

    【讨论】:

    • 谢谢!!但我不知道如何修复 (list (car l)) 部分... :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多