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!

1
  • This problem is absolutely begging for the application of the Design Recipe (cf. htdp.org ). Specifically: what's the data definition for your input? Jan 11, 2010 at 22:37

1 Answer 1

3

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.