tags:

views:

49

answers:

1

Hello, 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?

+6  A: 

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
ygrek
But will this allow a comparison between Int of int and Float of float (I think that's what the OP is asking, though he writes: Int of int < Float of int ... but I wonder if that's a type as his type specifies Float of float)
aneccodeal
The problem is that I need to provide a way to order different kinds of datatype to be able to use the `Set`, that's why I was wondering if forcing a specific hierarchy (eg `None < Int < Float < Complex ..`) is an acceptable way to do it or if I have to find another way..
Jack
@Jack `Pervasives.compare` will automatically do a sensible comparison; I believe it will implement the hierarchy you propose on its own. No need to define your own comparison function unless you have particular needs.
Michael E
As Michael E said - `compare` is a generic polymorphic structural comparison function - it will define a total ordering on any values (by magic) - use it unless you have a specific requirement on ordering (in case of `Set` this only influences the `min_elt` and `max_elt` functions). NB exception to the above : `compare` cannot compare functions and will raise exception at runtime.
ygrek