Is it possible to pattern match against a Set like as against a List? For example consider the following code:
module MySet = Set.Make (struct ... end)
match MySet.empty with
| MySet () -> "Empty Set"
| MySet (x) -> "Set with exactly one element"
| MySet (x, y, _) -> "Set with at least two elements"
Of course, a set is an unordered data type, so I cannot expect to get the same binding to x
and y
in each run (although one might implement this functionality via the compare function, but we keep it simple for this question).
Why do I ask this question? Sometimes I want to check if a Set is empty, or if it contains exactly one element and then continue with exactly this element, or if it contains two elements and so forth.
My first implementation compared the cardinality of the set and I then proceeded with choosing one element, or two elements and so forth but this is somehow cumbersome and I hoped that pattern matching would produce more readable/maintainable code.