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.

Wednesday, September 15, 2010

going through "elements of ml programming"

Just finished chapter 2 (“Getting Started in ML”). One question has me stumped. We're given a bunch of type expressions and asked to provide examples of values that have those types. The one that I can't seem to find an example for is:

((int * int) * (bool list) * real) * (real * string)

I can easily construct an example that matches

((int * int) * bool list * real) * (real * string)

but what has the type (bool list)? A tuple with one element is really just a parenthesized expression (consider the equivalent expressions a + (b * (c)) and a + (b * c)).

I'm doing the exercises with Moscow ML.