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?
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.
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.
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.
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)
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With