Code: Select all

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

Thanks.

I use the following function to calculate the maximum nesting deep of a list:
Is there a better/faster way to do this?

Thanks.

Code: Select all

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

Thanks.

Here's another way to do it.

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

Code: Select all

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

(λx. x x) (λx. x x)

The magic of "map" :-)

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

Code: Select all

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

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)

Wow!!!

Thanks fdb

Thanks fdb