Write a function min_max : int list -> int * int that takes a non-empty list of numbers, and returns a pair (min, max) of the minimum and maximum of the numbers in the list.
Here is what I've written so far.
fun min_max (n : int list) =
if null n then NONE
else
let
fun max (n : int list) =
if null (tl n) then hd n
else
let
val mn = max (tl n)
in
if hd n > mn then hd n
else mn
end
fun min (n : int list) =
if null (tl n) then hd n
else
let
val mix = min (tl n)
in
if hd n < mix then hd n
else mix
end
in
SOME (min :: max)
end;
Most of what you've written works. Your
minandmaxfunctions work.This doesn't work, though.
This is not how you construct a "pair" or "tuple" of values. Rather:
Moreover, this is now just two functions. You need to apply those functions to your list
nto get the results you're looking for.As a suggestion, you can use pattern-matching to simplify your code considerably by avoiding
hdandtland replacing the conditional test on the tail. For instance:But we know that
h::trepresents a list with at least two elements, so we can bind names to those elements in our pattern.If we evaluate this on a list, we can see how it would proceed.
This also has the benefit of being tail-recursive.