I’ve written a function to get the maximum value from a list of nested lists, I have the general form of the function down right; it works on flat lists and nested lists but seems to fail when there are sibling nested lists.
Here is my code:
(define (multi-max array)
(cond
((null? array) 0)
((number? (car array))
(if (> (car array) (multi-max (cdr array)))
(car array)
(multi-max (cdr array))))
((pair? (car array))
(multi-max (car array)))
(else
(multi-max (cdr array)))))
Here is a test list that it fails on: (multi-max '(1 9 83 9 (332 (334) (2 3 4224))))
I’m not sure where I’m going wrong, logically, some help would be nice!
I didn’t locate the logical error so I rewrote it in a more recursive way 🙂
It’s important to identify the recursive parts first before writing our function.
multi-maxcan be defined recursively asmulti-max = max(multi-max(car), multi-max(cdr))(multi-max '(1 9 83 9 (332 (334) (2 3 4224))))now outputs
4224.Edit: Ok, I think I found the error:
The code ignores the
(cdr array)in the(pair? )part and(car array)in the
(else )part.It should be:
(*) note that the
(pair? )is removed.