Hot to declare an empty Map/dictionary?

Viewed 1978

I would like to initialize a recursive function with a Map. To declare a read-only dictionary with value we can do:

let dictionary1  = dict [ (1, "a"); (2, "b"); (3, "c") ]       

Try it online!

Now, I would like to create an empty dictionary. How to achieve that?

I am looking fo something like:

let dictionary1 = {} // <- ok this is js
let (stuff, dictionary2) = parseRec("whatever", dictionary1)
3 Answers

You can do:

let dictionary1  = dict []

for elem in dictionary1 do
   printfn "Key: %d Value: %s" elem.Key elem.Value

and that gives you an empty dictionary.

The printfn usage reveals to the type inference engine the correct types of key and value.

If you want to be explicit then you can specify the types in several ways:

let dictionary1 = dict Seq.empty<int * string>
let dictionary1 = dict ([] : (int * string) list)
let dictionary1 = dict [] : System.Collections.Generic.IDictionary<int, string>
let dictionary1 : System.Collections.Generic.IDictionary<int, string> = dict []

If you need a .NET Dictionary, you can use a .net Dictionary:

let dictionary1 = new System.Collections.Generic.Dictionary<int, string>()

Since you ask for Map/Dictionary, here is two other solutions for Map:

let dictionary1 : Map<int, string> = Map.empty
let dictionary1 = Map<int, string> []

source

Related