First, I should make it clear that this is required for an academic project. I am trying to find the maximum number of child nodes for any node in a tree, using Common Lisp.
My current code is shown below – I’m not 100% on the logic of it, but I feel it should work, however it isn’t giving me the required result.
(defun breadth (list y)
(setf l y)
(mapcar #'(lambda (element)
(when (listp element)
(when (> (breadth element (length element)) l)
(setf l (breadth element (length element)))
))) list)
l)
(defun max-breadth(list)
(breadth list (length list))
)
As an example, running
(max-breadth '(a ( (b (c d)) e) (f g (h i) j)))
should return 4.
Edit:
Trace results and actual return values, forgot these:
CG-USER(13): (max-breadth '(a ( (b (c d)) e) (f g (h i) j)))
0[6]: (BREADTH (A ((B (C D)) E) (F G (H I) J)) 3)
1[6]: (BREADTH ((B (C D)) E) 2)
2[6]: (BREADTH (B (C D)) 2)
3[6]: (BREADTH (C D) 2)
3[6]: returned 2
2[6]: returned 2
1[6]: returned 2
1[6]: (BREADTH (F G (H I) J) 4)
2[6]: (BREADTH (H I) 2)
2[6]: returned 2
1[6]: returned 2
0[6]: returned 2
2
Does anyone have any ideas where I’m going wrong? I suspect it’s related to the second conditional, but I’m not sure.
First, standard formatting:
Your problem is the
(setf l y), which should give you a warning aboutlbeing undefined.Setfshould not be used on unbound variables. Useletto make a lexical scope:Then, instead of two nested
when, use a single one andand:I find
dolistmore concise here:The parameter
yis always the length of the parameterlist, so this call can be simplified. You also do not need to aliasy:You could eliminate the double recursive call through a
let, but we can usemaxhere:You could also use
reducefor this: