I'm currently studying SML and I'm having a hard time understanding the code below
fun good_max (xs : int list) =
if null xs
then 0
else if null (tl xs)
then hd xs
else
(* for style, could also use a let-binding for (hd xs) *)
let val tl_ans = good_max(tl xs)
in
if hd xs > tl_ans
then hd xs
else tl_ans
end
hd xs
is of type int
and tl_ans
, I think is of type list
.
Why does this code work? How does the system evaluate the recursion?
It would be great if you could use xs = [3, 4, 5]
to show me how this works.
max
function already exists in the standard library asInt.max
. Also, the right-hand side of the third case could obviously be simplified to justmax(x, goodMax xs)
-- I didn't do that to demonstrate how reduction inside alet
works. Finally, I would suggest rather throwing an exception in the empty case, since 0 is not quite right as a result. Altogether, you can then express the function with a fold as simplyfun goodMax [] = raise Empty | goodMax(x::xs) = List.foldl Int.max x xs
. - Andreas Rossberg