Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27296

OCaml map of int keys :: where is the 'simple' int module to use with the Map.Make functor?

I need an OCaml map with keys of type int so I am using Map.Make to create one. However it seems that the standard modules 'only' provide modules like Big_int, Int32, Int64 and Nativeint which require conversions. So I have to do things like:

module IntMap = Map.Make(Int32) 
let a_map = IntMap.add (Int32.of_int 0) "zero" IntMap.empty ;;

... which I would rather avoid or define my own silly Int module do deal with simple int literals or values without requiring conversion functions:

module Int = struct                       
   type t = int                                              
   let compare x y = if x < y then -1 else if x > y then 1 else 0 end ;;  
module IntMap = Map.Make(Int) 
let a_map = IntMap.add 0 "zero" IntMap.empty ;;

Am I missing something obvious here?

Upvotes: 20

Views: 7098

Answers (5)

Chris
Chris

Reputation: 36650

As of OCaml 4.08 (released June of 2019) the standard library includes the Int module which fulfills this need.

module IntMap = Map.Make (Int)

Upvotes: 1

actionshrimp
actionshrimp

Reputation: 5229

If you happen to use containers already (which I think is a bit more commonplace since previous answers were written), you can conveniently use the containers 'primitive' modules along with the CCMap module to achieve this, e.g.:

module ByInt = CCMap.Make(CCInt)

Upvotes: 0

You can build IntMap with a one-liner. If you don't mind using third-party libraries, Jean-Christophe Filliâtre's Patricia tree library (Ptmap) is a little more efficient (and similarly Ptset for sets of OCaml integers).

Upvotes: 2

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

I dont think you're missing anything, there's no standard module for this. I believe the BatInt module of OCaml Batteries Included does what you want.

(Edited to add: it's true, I myself use the method suggested by Thomas!)

Upvotes: 7

Thomas
Thomas

Reputation: 5048

The simplest way to have an int map is to do the following:

module IntMap = Map.Make(struct type t = int let compare = compare end)

Upvotes: 31

Related Questions