【问题标题】:LISP Determine the depth of a listLISP 确定列表的深度
【发布时间】:2019-11-28 20:56:53
【问题描述】:

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

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

等等。

这是我迄今为止所写的,它仅适用于线性列表 (depth = 1) 和 depth = 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))
    )
)

【问题讨论】:

  • 有意义吗? AND:你的程序正在做其他事情。
  • 首先您需要更好地描述问题。列表的深度是多少?然后你需要想出更多不同的例子。也许十个或更多。示例应包括极端案例。然后回过头来想出如何解决它并尝试编写代码。
  • 深度是嵌套列表的数量(列表中的列表)例如:(1 2 3) -> 没有嵌套列表,所以深度 = 1; (1 (2) 3) -> (2) 是主列表中的嵌套列表,因此深度 = 2; (1 2 ( 3 (4))) -> 深度为 3,因为 (4) 是列表 (3 (4)) 中的嵌套列表,深度 = 2
  • ( ((1)) ((((((2))))) ) => 深度 = 6. ( ((((3))) ((2)) (1) ) = > 4. 用肉眼确定的一种简单方法是为每个 '(' 加 1,为每个 '1' 减 1(一种动态编程),最大值是深度。对于第一个示例 0 +1 = 1 , 1+1 = 2, 2 + 1 = 3, 3 - 1 = 2, 2 - 1 = 1, 1 + 1 = 2, 2 + 1 = 3, 3 + 1 = 4, 4 + 1 = 5, 5 + 1 = 6, 6 - 1 = 5, 5 - 1 = 4, 4 - 1 = 3, 3 - 1 = 2, 2 - 1 = 1, 1 - 1 = 0
  • 最大的想法

标签: list lisp common-lisp depth clisp


【解决方案1】:

列表的深度为:

(+ 1 (reduce #'max (mapcar #'depth list) :initial-value 0))

计算所有深度,然后取最大值。添加一个。非列表的深度为 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

【讨论】:

    【解决方案2】:

    我正在考虑这个问题,我意识到你可以很好地概括它。如果你有两个操作,along 沿着某个对象移动光标anddownwhich moves down into elements of it, as well as anapplicable?predicate which tells you ifdowncan be called, then you can write this rather general function to compute thedown`-某物的深度(这是在 Racket 中,因为 Lisp 更容易-1-ness):

    (define (dual-depth thing down along applicable?)
      ;; given dual operations down and along, and a test, applicable?,
      ;; return the down depth of thing.
      ;; This is zero if applicable? is false, and can fail to terminate if
      ;; the structure has cycles either in down or along.
      (let dd ([it thing])
        (if (applicable? it)
          (let dd-loop ([tail it] [so-far 0])
            (if (not (applicable? tail))
                so-far
                (dd-loop (along tail) (max so-far (+ 1 (dd (down tail)))))))
          0)))
    

    然后

    (define car-depth
      ;; the depth of a cons tree thought of the way it is written
      (λ (l) (dual-depth l car cdr cons?)))
    
    (define cdr-depth
      ;; the depth of a cons tree thought of the other way
      (λ (l) (dual-depth l cdr car cons?)))
    

    甚至:

    (define car-depth
      (curryr dual-depth car cdr cons?))
    
    (define cdr-depth
      (curryr dual-depth cdr car cons?))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      相关资源
      最近更新 更多