Map.of_bindings function?

Hello!

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

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

(see https://package.elm-lang.org/packages/elm/core/latest/Dict#fromList )
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: https://ocaml.org/releases/4.10/htmlman/libref/Map.Make.html

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 = 
    List.fold_left 
        (fun acc (k, v) ->  StringMap.add k v acc)
        StringMap.empty

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”?)

Regards,

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

3 Likes

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
2 Likes