Lisp中的深度反转功能

typ*_*pos 1 lisp common-lisp

我想在Lisp中编写一个深度反向函数,只依赖于Lisp提供的原始反向函数,以及其他一些常见的东西.我认为使用地图更容易,例如:

(defun deep-reverse (list)
  (if (listp list)
      (mapcar #'deep-reverse
              (reverse list))
      list))
Run Code Online (Sandbox Code Playgroud)

但是如果不使用这些地图或其他结构呢?仅仅依靠的东西,如if,reverse,append,null,nil,listp,atom,cons,car,cdr,等基本的东西.我可以做一个级别的反向,像这样:

(defun reverse (list)
  (if (null list)
     'nil
      (append (reverse (cdr list))
              (cons (car list) 'nil))))
Run Code Online (Sandbox Code Playgroud)

但是我如何才能实现深度逆转呢?深度反转的意思是,如果函数的输入是((1 2 3) (4 5 6)),输出应该是((6 5 4) (3 2 1)).

sds*_*sds 6

你快到了:

(defun deep-reverse (list)
  (if (consp list)
      (nconc (deep-reverse (cdr list))
             (list (deep-reverse (car list))))
      list))
(deep-reverse  '((1 2 3) (4 5 6)))
==> ((6 5 4) (3 2 1))
Run Code Online (Sandbox Code Playgroud)

与您的版本相比,我需要做一些更改:

  1. 呼叫deep-reverse carcdr.
  2. 使用nconc而不是append避免不必要的消耗.
  3. 重命名reversedeep-reverse.
  4. 分支递归consp,而不是null.