LISP确定列表的深度

Nor*_*rby 1 lisp clisp list common-lisp depth

我正在尝试编写一个确定列表深度的函数。因此对于

  • (1 2 3 4)=> 1
  • (1 2 3(4))=> 2
  • (1 2 3(4(5)))=> 3

等等。

这是我到目前为止编写的内容,它仅适用于线性列表(深度= 1)和深度为2的列表。

我认为我已经接近正确的解决方案,但我觉得自己缺少一些东西。

(defun detlen (lst count)
    (
        cond
            ((null lst) count)
            ((LISTP (car lst)) (setq count (+ count 1)) (detlen (cdr lst) count))
            (t (detlen (cdr lst) count))
    )
)
Run Code Online (Sandbox Code Playgroud)

Rai*_*wig 6

列表的深度为:

(+ 1 (reduce #'max (mapcar #'depth list) :initial-value 0))
Run Code Online (Sandbox Code Playgroud)

计算所有深度,然后取最大值。加一。非列表的深度为0。

CL-USER 195 > (defun depth (list)
                (if (listp list)
                    (+ 1 (reduce #'max (mapcar #'depth list)
                                 :initial-value 0))
                    0))
DEPTH

CL-USER 196 > (depth '(((2)) (1)))
3
Run Code Online (Sandbox Code Playgroud)