Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in F#, How do you merge 2 Collections.Map instances?

Tags:

collections

f#

I am trying to merge two Maps, but there is no built in method for joining Collections. So how do you do it?

like image 859
klactose Avatar asked Oct 20 '10 04:10

klactose


People also ask

What temperature in Fahrenheit is 50 C?

Answer: 50° Celsius is equal to 122° Fahrenheit.

What does 37.4 Celsius mean in Fahrenheit?

37.4 °C = 99.4 °F 37.6 °C = 99.6 °F. 37.7 °C = 99.8 °F. 37.8 °C = 100.0 °F. 37.9 °C = 100.2 °F.


1 Answers

You can implement this using Map.fold and Map.add, since add is actually add/replace:

let map1 = Map.ofList [ 1, "one"; 2, "two"; 3, "three" ]
let map2 = Map.ofList [ 2, "two"; 3, "oranges"; 4, "four" ]


let newMap = Map.fold (fun acc key value -> Map.add key value acc) map1 map2

printfn "%A" newMap 

Probably the reason merge isn't provided out of the box is that you need to deal with key conflicts. In this simple merge algorithm we simple take the key value pair from the second map, this may not be the behaviour you want.

like image 85
Robert Avatar answered Sep 23 '22 20:09

Robert