如何在方案中找到S-expression的最大嵌套深度?

时间:2014-05-06 01:49:04

标签: functional-programming scheme lisp racket

例如

(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))))))

1 个答案:

答案 0 :(得分:6)

这有点简单。试一试:

(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