signature NATSET = sig (* a "set" is a set of natural numbers: * e.g., {1,11,0}, {}, and {29} *) type set (* empty is the empty set *) val empty : set (* single(x) is {x}. Requires: x >= 0 *) val single : int -> set (* union is set union. *) val union : set*set -> set (* contains(x,s) is whether x is a member of s *) val contains: int*set -> bool (* size(s) is the number of elements in s *) val size: set->int end structure NatSet :> NATSET = struct type set = int list (* Abstraction Function: The list [a1,...,an] represents the smallest set containing all the elements a1 through an. The list may contain duplicates. The empty list represents the empty set. RI: All elements of the list are >= 0 *) val empty = [] fun single(x) = [x] fun union(s1,s2) = s1@s2 fun contains(x,s) = case s of [] => false | h::t => x = h orelse contains(x,t) fun size(s) = case s of [] => 0 | h::t => size(t) + (if contains(h,t) then 0 else 1) end structure NatSetNoDups :> NATSET = struct type set = int list (* AF: The list [a1,...,an] represents the set {a1,...,an}. RI: No duplicate or negative elements. *) val empty = [] fun single(x) = [x] fun contains(x,s) = case s of [] => false | h::t => x = h orelse contains(x,t) fun union(s1, s2) = foldl (fn (x,s) => if contains(x,s) then s else x::s) s1 s2 fun size(s) = List.length(s) end structure NatSetVec :> NATSET = struct type set = bool vector (* AF: The vector v represents the set of numbers i such that sub(v,i) = true *) val empty:set = Vector.fromList [] fun single(x) = Vector.tabulate(x+1, fn(y) => x=y) fun union(s1,s2) = let val len1 = Vector.length(s1) val len2 = Vector.length(s2) fun merge(i) = (i < len1 andalso Vector.sub(s1, i)) orelse (i < len2 andalso Vector.sub(s2, i)) in Vector.tabulate(Int.max(len1, len2), merge) end fun contains(x,s) = x >= 0 andalso x < Vector.length(s) andalso Vector.sub(s,x) fun size(s) = Vector.foldl (fn (b,n) => if b then n+1 else n) 0 s end