【问题标题】:How to find the maximum nesting depth of a S-expression in scheme?如何在方案中找到 S 表达式的最大嵌套深度?
【发布时间】:2014-05-06 21:48:22
【问题描述】:

例如

(nestFind '(a(b)((c))d e f)) => 3

(nestFind '()) => 0

(nestFind '(a b)) => 1

(nestFind '((a)) )=> 2

(nestFind '(a (((b c d))) (e) ((f)) g)) => 4

这是我迄今为止尝试过的,但它不能正常工作:

(define (nestFind a)
  (cond
    ((null? a)0)
    ((atom? a)0)
    ((atom? (car a))(+ 1 (nestFind (cdr a))))
    (else
     (+(nestFind (car a))(nestFind (cdr a))))))

【问题讨论】:

    标签: functional-programming scheme lisp racket


    【解决方案1】:

    这有点简单。试试这个:

    (define (nestFind lst)
      (if (not (pair? lst))
          0
          (max (add1 (nestFind (car lst)))
               (nestFind (cdr lst)))))
    

    诀窍是使用max 找出递归的哪个分支是最深的,注意每次我们在car 上递归时都会增加一层。或者,一个更接近您预期的解决方案 - 但再次证明,max 很有帮助:

    (define (nestFind lst)
      (cond ((null? lst) 0)
            ((atom? lst) 0)
            (else (max (+ 1 (nestFind (car lst)))
                       (nestFind (cdr lst))))))
    

    无论哪种方式,对于示例输入,它都会按预期工作:

    (nestFind '())
    => 0
    (nestFind '(a b))
    => 1
    (nestFind '((a)))
    => 2
    (nestFind '(a (b) ((c)) d e f))
    => 3
    (nestFind '(a (((b c d))) (e) ((f)) g))
    => 4
    

    【讨论】:

    • 是否可以不使用max.
    • @xmantra23 我不这么认为,要么是 max 要么是 if 表达式基本相同。毕竟我们对添加元素的数量(这就是你正在做的)不感兴趣,只是想找到最深的子列表的深度
    • (or (null?lst) (not (pair?lst))) 可以写成 (not (pair?lst))。 (null?lst) 和 (atom?lst) 也是如此。
    • @jJ' 你是对的,谢谢!这更简化了一些事情。我更新了我提出的解决方案,但我将保留另一个原样,因为它更符合 OP 的初始实施。
    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 2018-04-14
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 2012-03-23
    • 2015-02-20
    • 1970-01-01
    相关资源
    最近更新 更多