I'm trying to create a dictionary in a functional way. I played a bit with it and was able to concatenate two dictionaries with this code:
let d1 = dict [(1, "one"); (2, "two")]
let d2 = dict [(4, "four")]
let d = List.ofSeq d1 @ List.ofSeq d2
Is this the correct way of working with immutable dictionaries in F#? It seems a bit complicated.
The dict
function is mostly a helper that creates a dictionary from a list if you already have a list containing all the items. It isn't all that useful in situations when you want to add elements - that is, create new dictionary containing all elements of the original one and also some new elements.
In that case, it is better to use the Map
type.
// Create map from a list
let m1 = Map.ofSeq [ (1, "one"); (2, "two") ]
// Create map from original map by adding one element
let m2 = m1.Add(4, "four")
To add all elements of m1
to m2
, you would probably write:
let newM2 = m1 |> Seq.fold (fun m (KeyValue(k, v)) -> Map.add k v m) m2
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