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)
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 []
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
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