I want to use OCaml to generates sets of data and make comparisons between them. I have seen the documentation for Module types like Set.OrderType, Set.Make, etc, but I can’t figure out how to initialize a set or otherwise use them.
I want to use OCaml to generates sets of data and make comparisons between
Share
Sets are defined using a functorial interface. For any given type, you have to create a
Setmodule for that type using theSet.Makefunctor. An unfortunate oversight of the standard libraries is that they don’t defineSetinstances for the built-in types. In most simple cases, it’s sufficient to usePervasives.compare. Here’s a definition that works forint:The module
IntSetwill implement theSet.Sinterface. Now you can operate on sets using theIntSetmodule:Note that you don’t have to explicitly define the input structure for
Set.Makeas anOrderedType; type inference will do the work for you. Alternatively, you could use the following definition:This has the advantage that you can re-use the same module to instantiate a
Map:You lose some genericity in using functors, because the type of the elements is fixed. For example, you won’t be able to define a function that takes a
Setof some arbitrary type and performs some operation on it. (Luckily, theSetmodule itself declares many useful operations onSets.)