Scheme function find max list

In Scheme, loops are usually constructed by using recursion, not by using a 'while' or 'for' statement as in C or Java.

To answer this question in Scheme, you'd observe that the largest element of a list is the greater of these two things:

- the first element in the list, and

- the largest element from the rest of the list

You would also observe that if a list contains only a single item, then that item must be the largest element in that list.

From these observations you can construct a function that grabs and remembers the first item of its argument list and then makes a recursive call to itself, passing only the tail of its argument list to that call. The recursion will continue in this way until the passed-in list contains only a single element. The function can then return the value of that single element, thereby ending the recursion. The caller can now compare that result to its remembered head value and then return the larger of those two values. When the entire recursion has unwound, the result will be the largest element from the entire list.

It would look something like this:

(define max-in-list (lambda (ls)

(let ( (head (car ls)) (tail (cdr ls)))

; list contains only one item, return it

; else find largest item in tail

(let ((max-in-tail (max-in-list tail)))

; return the larger of 'head' and 'max-in-tail'

(if (> head max-in-tail)

This program could be written in a slightly different way that would allow for more efficient execution, but that version wouldn't be quite as easy to understand. For now, simpler is better.