How to find the maximum nesting depth of a S-expression in scheme?

拈花ヽ惹草 提交于 2021-02-05 07:33:20

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/23484728/how-to-find-the-maximum-nesting-depth-of-a-s-expression-in-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!