例如

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

最佳答案

有点简单试试看:

(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

09-04 20:19