Create empty Map with given key and value types?

I’m writing my first “real” OCaml program, and I’m looking for a way to create a (global ref) empty Map, and at the same time specify the type of both the keys and the values. When I do like this:

module StringMap = Map.Make (String)
let vector_map = ref StringMap.empty

… then only the type of the keys are given (String). I would also like to specify the value type to be an Array of floats. Is that possible before I know the length of those arrays?

Certainly: it is always possible to add a type constraint to such definitions:

let vector_map: float array String.Map.t ref = ref StringMap.empty

It can even be considered good practice with toplevel definition since it avoids introducing a weak type variable, that could lead to a compiler error.
Indeed compiling a file æ.ml with just

(* a.ml *)
module StringMap=Map.Make(String)
let x = ref StringMap.empty

would yield an error

File "a.ml", line 2, characters 4-5:
Error: The type of this expression, '_a StringMap.t ref,
       contains type variables that cannot be generalized
2 Likes

Thanks a lot, octachron! You saved me lots of frustration. I will study that type construction (float array StringMap.t ref) so that I can really understand it.
What I find somewhat problematic with much of the available OCaml tutorials, is that they focus very much on the interactive use of the REPL, and not so much on what’s needed for a source file to compile.

By the way, if you want an imperative map you may want to consider using a Hashtbl