Thursday, September 16, 2010

stopping at 3.2, it's late

Today's problem:

Compute the largest element of a list of reals.
Your function need not behave well if the list is empty.

My solution was to define two functions:

fun max (a:real) b =
     if a > b then a else b;
fun maxls L =
    if (tl L) = nil then (hd L)
    else max (hd L) (maxls (tl L));

The solution on the website is

fun maxList(L: real list) =
    if tl(L) = nil                             (* L is a single element *)
        then hd(L)                             (* the single element is the maximum *)
    else                                       (* assume there are at least 2 elements *)
        if hd(L) > hd(tl(L))                   (* the first element exceeds the second *)
            then maxList(hd(L)::tl(tl(L)))     (* eliminate second element *)
            else maxList(tl(L));               (* eliminate first element *)

My way's not as efficient, but it's easier to follow.

No comments: