Jack
Jack

Reputation: 133609

Heterogeneous sets in OCaml

suppose I have a type defined as

type value =
      None
    | Int of int
    | Float of float
    | Complex of Complex.t
    | String of string
    | Char of char
    | Bool of bool

and I want to be able to work with Sets of these values. From what I understood I have to use the functor to concretize the Set module with a concrete type and its associated ordering.

How should I do it in this example? Since value cannot be used directly inside the Set.Make functor?

Then of course I need to be able to give a full ordering of these values so I should invent something like giving a predefined order to different types, and then ordering them by their effective value.. am I right?

So for example I can decide to have Int of int < Float of int and Int x < Int y if x < y. Is it a practical approach to what I'm trying to achieve?

Upvotes: 3

Views: 403

Answers (1)

ygrek
ygrek

Reputation: 6697

Set.Make functor takes the module with signature Set.OrderedType :

module type OrderedType = sig type t val compare : t -> t -> int end

For comparison you can use Pervasives.compare if you don't have any requirements on the order and results returned by min_elt/max_elt. So the parameter to the functor can be as simple as :

module T = struct type t = value let compare = compare end

Upvotes: 7

Related Questions