CL-USER> (nivel '((a) b c) 0)
; Evaluation aborted.
CL-USER>
-returned 'b is not of type list'
CL-USER> (nivel '((a) (b) (c)) 0)
1
CL-USER>
-function requires all root level leaves to be lists.
CL-USER> (nivel '((a) (b (d)) (c)) 0)
2
-works for this particular tree
CL-USER> (nivel '((a) ((b) d) (c)) 0)
; Evaluation aborted.
'd is not of type list'
CL-USER> (nivel '((a (d)) (b) (c)) 0)
1
CL-USER>
-mises d sub-branch of first root leaf a
Here is the code I wrote, which is made a little different by using if, progn and listp instead of cond and atom; is also messy and probably has more code than needed, but it works:
Code: Select all
(defun levelnum(x)
(+ 0
(if (atom x) 0
(progn
(+
(if
(>
(if (not (null (cdr x))) (+ 0 (levelnum (cdr x)))0)
(if (listp (car x)) (+ 1 (levelnum (car x )))0))
(if (not (null (cdr x))) (+ 0 (levelnum (cdr x)))0)
(if (listp (car x)) (+ 1 (levelnum (car x ))) 0)))))))
1
CL-USER> (levelnum '((a) (b) (c)))
1
CL-USER> (levelnum '((a) (b (d)) (c)) 0)
2
CL-USER> (levelnum '((a) ((b) d) (c)) )
2
CL-USER> (levelnum '((a (d)) (b) (c)) )
2
CL-USER>
Also, look at these comparisons:
CL-USER> (levelnum '((a) (b) (c) (d (e))))
2
CL-USER> (nivel '((a) (b) (c) (d (e))) 0)
1
CL-USER> (levelnum '((a) ((k (o (r))) (d) ) (c (n))) )
4
CL-USER> (nivel '((a) ((k (o (r))) (d) ) (c (n))) 0)
2
Do you see the differences in the code that caused these result differences?