4

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.

Max Maier
  • 985
  • 6
  • 16

1 Answers1

3

No. The implementation of Set is hidden therefore you cannot directly pattern-match the value. You have to use functions defined in Set module to deconstruct it. Check set.mli. Without much details of your problem, we cannot say which function you should use. Probably choose and split, or iter or fold, or simply elements.

Set requires an ordering of element values and it is implemented as a binary tree where the elements are sorted in that order. Therefore these functions of Set should work always the same for equal sets.

camlspotter
  • 8,990
  • 23
  • 27
  • Thanks for explanation! I had hoped that pattern matching somehow works but you are totally right, since the implementation is hidden, we cannot deconstruct a set. – Max Maier Apr 07 '15 at 08:27