Question

Core library for the OCaml language comes with very useful Map and Table modules. I know how to define my own type if I want to use a map from some built-in type:

type mytype = int String.Map.t (* A mapping from strings to integers *)

I also know how to define a custom map with polymorphic compare:

type mytype = (string, string) Map.Poly.t (* A map from strings to strings *)

What I don't know is how to define custom map using non-polymorphic compare from my own type to my own type. E.g. suppose I have

type row_t = Row of int
type column_t = Column of int
(* I want a map from rows to columns *)
type mymap_t = (row_t, column_t, ???) Map.t

I understand that the third argument should be the comparator, yet I don't know what to put inside: both Int.comparator and Int.comparator_witness fail to give the desired result.

Was it helpful?

Solution

You can refer to the blog post Ashish mentioned.

However I usually prefer more "automatic" way to generate Maps and Sets for custom structures when using Core (thanks to Core syntax extensions).

Here is a small example:

module T = struct
  type t = Row of int
  with sexp, compare
end
include T
include Comparable.Make(T)

So this will generate all comparison functions (and other useful functions) and basic data structures that you usually need:

type t = T.t = Row of int
...
val (>) : T.t -> T.t -> bool = <fun>    (* compare functions *)
val (<) : T.t -> T.t -> bool = <fun>
val equal : T.t -> T.t -> bool = <fun>
val compare : T.t -> T.t -> int = <fun>
val min : T.t -> T.t -> T.t = <fun>
val max : T.t -> T.t -> T.t = <fun>
...
module Map :  (* non-polymorphic Map module *)
...
end
module Set :  (* non-polymorphic Set module *)
...
end

and a lot more. So basically you can use a non-polymorphic map afterwards:

type column_t = Column of int
let map = Map.singleton (Row 1) (Column 2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top