Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ocaml

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?

like image 997
Marcus Junius Brutus Avatar asked Apr 12 '12 21:04

Marcus Junius Brutus


People also ask

What does map do in OCaml?

Introduction to OCaml Map. In OCaml, we can use the map function with the list library we have already; this function is the part of the list in OCaml so that it can be called on the list. This function takes two arguments as the parameter and bit tricky to understand as well.

What are modules OCaml?

In OCaml, every piece of code is wrapped into a module. Optionally, a module itself can be a submodule of another module, pretty much like directories in a file system - but we don't do this very often.

What are functors in OCaml?

A functor is a module that is parametrized by another module, just like a function is a value which is parametrized by other values, the arguments. It allows one to parametrize a type by a value, which is not possible directly in OCaml without functors.


2 Answers

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)
like image 152
Thomas Avatar answered Nov 23 '22 11:11

Thomas


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!)

like image 38
Jeffrey Scofield Avatar answered Nov 23 '22 09:11

Jeffrey Scofield