Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with immutable dictionaries

Tags:

dictionary

f#

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.

like image 397
Max Avatar asked Nov 26 '10 14:11

Max


1 Answers

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
like image 57
Tomas Petricek Avatar answered Oct 31 '22 19:10

Tomas Petricek