I'm learning SML and trying to make a datatype, called mySet, that can be any list of ints or reals, but with no duplicates and in sequential order. So far, I've made the datatype and some functions that do what I need to a list and then return it within that datatype which work fine. But I realized that the constructor for the datatype could also be used instead which completely bypasses the requirements. For what I need, I can just use the function, but I'd really like to know if there's any way I can patch up that problem? If a list doesn't follow the requirements, most of my functions for the datatype wouldn't work right.
datatype 'a set = Set of 'a list | Empty;
(* takes (item, list) and removes any copies of item from list *)
fun cleanList(a, []) = []
|cleanList(a, b::rest) =
if b = a then cleanList(a, rest)
else
b::cleanList(a, rest);
(*uses cleanList to make a list with all the items, no copies*)
fun removeDup([]) = []
| removeDup(a::rest) =
let
val cleanRest = cleanList(a, rest);
in
a::removeDup(cleanRest)
end;
(*uses above 2 functions, then puts the list in order *)
fun makeSet([]) = Empty
|makeSet(inputList) =
let
val cleanList = removeDup(inputList)
val sortedList = ListMergeSort.sort (fn(x,y) => x > y) cleanList;
in
Set(sortedList)
end;
val testList = [27, 81, 27, 3, 4, 5, 4, 27, 81, 3, 3, 7];
makeSet(testList); (* returns Set [3,4,5,7,27,81] *)
Set([1,1,1,1,1,1]); (*Set [1,1,1,1,1,1] which I don't want to allow *)