How do I use sets in OCaml?
The Set.S
is a module type not a module. You can open only modules. In fact module Set
contains three elements:
- module type
OrderedType
that is a type of modules that implement ordered types; - module type
S
that is a type of modules that implementSet
data structures; - functor
Make
that takes a module of typeOrderedType
and returns a module of typeS
.
For example, to create a module, that implements a set for integers, you can do the following:
module Int = struct
type t = int
(* use Pervasives compare *)
let compare = compare
end
module Ints = Set.Make(Int)
Other libraries, like Janestreet's Core library, provide sets out of box, for example, Core library has an Int
module that is already charged with sets, maps, hashtables, so it can be accessed without any functors:
open Core.Std
let nil = Int.Set.empty
Or, in the modern (2018-2019) version of Janestreet Core or Base libraries, you can use polymorphic sets/maps, which require you to specify the module for keys only when a new set or map is created, e.g., like this
open Base (* or Core, or Core_kernel *)
let nil = Set.empty (module Int)
let one = Set.add nil 1
let two = Set.singleton (module Int) 2
You have to Make
a set module from the Set functor.
module SI = Set.Make(struct type t = int let compare = compare end)
Then you can have a set of ints:
# let myset = SI.add 3 SI.empty;;
val myset : SI.t = <abstr>
# SI.elements myset;;
- : SI.elt list = [3]