views:

354

answers:

1

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!

+3  A: 

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-max can be defined recursively as multi-max = max(multi-max(car), multi-max(cdr))

(define (multi-max array)
  (cond ((pair? array) (max (multi-max (car array)) (multi-max (cdr array))))
        ((number? array) array)
        (else 0)))

(multi-max '(1 9 83 9 (332 (334) (2 3 4224))))
now outputs 4224.

Edit: Ok, I think I found the error:

...
((pair? (car array))
 (multi-max (car array)))
(else
 (multi-max (cdr array))))
...

The code ignores the (cdr array) in the (pair? ) part and (car array)
in the (else ) part.

It should be:

(else (max (multi-max (car array)) (multi-max (cdr array))))

(*) note that the (pair? ) is removed.

Nick D
Doh! Thanks dude!
Ixmatus