tags:

views:

86

answers:

2

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

+5  A: 

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.

Robert
Indeed this was exactly how I implemented this:
Massif
+5  A: 

Define the following function:

let join (p:Map<'a,'b>) (q:Map<'a,'b>) = 
    Map(Seq.concat [ (Map.toSeq p) ; (Map.toSeq q) ])

example:

let a = Map([1,11;2,21;3,31;])

let b = Map([3,32; 4,41;5,51;6,61;])

let c = join a b

and the result:

val c : Map<int,int> =
  map [(1, 11); (2, 21); (3, 32); (4, 41); (5, 51); (6, 61)]
Yin Zhu
Thanks! This works.
klactose