Another quick answer (a little more work will be needed if you want to handle duplicate values or have specific requirements regarding order) :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 

let toMap kvs =
    let addPair map (k, v) =
        match Map.tryFind k map with
        | None -> map |> Map.add k [v]
        | Some vs -> map |> Map.remove k |> Map.add k (v :: vs)
    kvs |> List.fold addPair Map.empty

let pairs = [(1,2); (1,5); (2,3); (3,4); (4,3); (3,9)]

toMap pairs

let merge map1 map2 =
    let addPair map k vs =
        match Map.tryFind k map with
        | None -> map |> Map.add k vs
        | Some vs' -> map |> Map.remove k |> Map.add k (vs @ vs')
    map1 |> Map.fold addPair map2

merge (Map.ofList [(1,[1;2;3]); (2,[1;4;5])]) (Map.ofList [(1,[5]); (2,[3])])
By on 2/2/2011 10:54 AM ()

Thanks guys! These helped me out a lot :)

By on 2/3/2011 8:03 AM ()

Hi,

My answer may not elegant. You can try it anyway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// first part of the question
type Stuff = {
     key : int
     value : int
    } 

let  things = [{key = 1; value = 2}; { key = 1; value =5}; {key =2; value =3}; {key =3; value =4}; {key =4; value =3}; {key =3; value =9}]

let result = things 
                |> Seq.groupBy (fun x -> x.key) 
                |> Seq.map (function a,b -> (a,[for i in b -> i.value]))

printfn "%A" result

// second part of the question
let map1 = [(1,[1;2;3]); (2,[1;4;5]) ]
let map2 = [(1,[5]); (2,[3])]

let merge = map1 @ map2 
            |> Seq.groupBy (function x,_ -> x)
            |> Seq.map (function x,y -> (x, y |> Seq.map (function _,z -> z)))
            |> Seq.map (function x,y -> (x, (y |> Seq.collect (fun x -> [ for i in x -> i])) |> Set.ofSeq |> Set.toList))

printfn "%A" merge
By on 2/2/2011 10:28 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper