Nesting level of a list

Started by cameyo, May 27, 2019, 01:50:50 AM

Previous topic - Next topic

cameyo

I use the following function to calculate the maximum nesting deep of a list:
(define (nesting lst)
  (cond ((null? lst) 0)
        ((atom? lst) 0)
        (true (max (+ 1 (nesting (first lst)))
                   (nesting (rest lst))))
  )
)

(nesting '(a (((b c (d)))) (e) ((f)) g))
;-> 5

Is there a better/faster way to do this?

Thanks.

rickyboy

#1
Here's another way to do it.


(define (nesting lst)
  (if (null? lst) 0
      (atom? lst) 0
      (+ 1 (apply max (map nesting lst)))))

You be the judge if it's "better".  Beware though that, although the code length is shorter, timing tests show that it is slightly *slower* than the original.  map has to create more cells, so the slowdown is probably due to that -- which also means increased space overhead!  So, maybe you should stick with the original. :)
(λx. x x) (λx. x x)

cameyo

#2
The magic of "map" :-)

fdb

#3
Not very elegant but maybe faster (for short lists I presume)


(define (nesting lst prev (t 0))
(if (= lst prev)
t
 (nesting (flat lst 1) lst (inc t))))


> (nesting '(a (((b c (d)))) (e) ((f)) g))
5

rickyboy

#4
Excellent, fdb!  Faster than mine by about a factor of 3 (on the sample input)! 2.5 times faster than the original.
(λx. x x) (λx. x x)

cameyo

#5
Wow!!!

Thanks fdb