Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hot to declare an empty Map/dictionary?

Tags:

f#

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)
like image 958
aloisdg Avatar asked Dec 23 '22 01:12

aloisdg


2 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 []
like image 137
AMieres Avatar answered Jan 04 '23 19:01

AMieres


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

like image 23
aloisdg Avatar answered Jan 04 '23 19:01

aloisdg