سؤال

for example

(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

this is what i tried so far but its not working properly:

(define (nestFind a)
  (cond
    ((null? a)0)
    ((atom? a)0)
    ((atom? (car a))(+ 1 (nestFind (cdr a))))
    (else
     (+(nestFind (car a))(nestFind (cdr a))))))
هل كانت مفيدة؟

المحلول

It's a bit simpler. Give this a try:

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

The trick is using max to find out which branch of the recursion is the deepest, noticing that each time we recur on the car we add one more level. Alternatively, a solution closer to what you intended - but once again, max proves helpful:

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

Either way, it'll work as expected for the sample input:

(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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top