I am quite new to SML and am trying to implement a selection sort. I am running into an uncaught empty error however and can't seem to see why.
fun removeMin lst =
let
val (m, l) = removeMin(tl lst)
in
if null (tl lst) then
(hd lst, [])
else if hd lst < m then
(hd lst, tl lst)
else
(m, hd lst::l)
end;
fun selectionSort [] = []
| selectionSort lst =
let
val (m, l) = removeMin(lst)
in
m::selectionSort(l)
end;
I would appreciate suggestions as to where my mistake is and how to fix it.
There is no base case in your recursion.
removeMinimmediately callsremoveMinwith the tail oflst. Eventuallylstwill be the empty list andtl lstwill fail with anEmptyexception. So you have to identify when you recursion should stop and add this case toremoveMin.You have actually identified this base case in your function:
if null (tl lst) then (hd lst, []). But this case should be checked right before the recursive call. By reorganising your function and getting rid of calls tohdandtlby using pattern matching constructs this is what I get: