Map.of_bindings function?


I’m coming from elm and with this language, we can do:

myDict : Dict String Int
myDict = Dict.fromList [("answer", 42), ("age", 10)]

(see )
a.k.a convert an association list to a dictionary (“Map” in the OCaml world).

I didn’t find such a function in the doc:

Did I not looked at the right place?

Of course, we I can write this function by hand like:

let map_of_bindings : (string * 'a) list -> 'a StringMap.t = 
        (fun acc (k, v) ->  StringMap.add k v acc)

But 1) it is too bad I can’t use it out of the box 2) it will be specific to the StringMap module I’ve created (but I’m a OCaml noob, maybe there is a way to say “define this function on a random instance of the Map functor”?)


Look at the of_seq and to_seq functions in List and Map.

With a list of bindings as you have, you could:
bindings |> List.to_seq |> Map.of_seq


You can also find such functions in stdlib extensions or replacements.

@c-cube could you be more specific? Would you have some links for those “stdlib extensions or replacements”?

  • containers (which I know best, thus the direct link)
  • batteries
  • base, core_kernel, core must have their own too