Group by with tuples in F#

f#

Solution

One solution:

let tuples = [("A",12); ("A",10); ("B",1);  ("C",2); ("C",1)]
tuples 
|> Seq.groupBy fst 
|> Seq.map (fun (key, values) -> (key, values |> Seq.sumBy snd))

Edit: ...or without piping:

let tuples = [("A",12); ("A",10); ("B",1);  ("C",2); ("C",1)]
Seq.map (fun (key, group) -> key, Seq.sumBy snd group)
        (Seq.groupBy fst tuples)

Problem

Suppose I have a list of tupples like these : ``` [("A",12); ("A",10); ("B",1); ("C",2); ("C",1)] ``` And I would like to do some kind of `groupby` how do I handle that? In pseudocode-SQL it should look something like this : ``` SELECT fst(tpl), sum(lst(tpl)) FROM [TupplesInList] GROUP BY fst(tpl) ``` yielding ``` [("A",22); ("B",1); ("C",3)] ``` I could make a Dictionary and add the ints if the key exist, but I can hardly believe that would be the best solution in a language as expressive as F#.

Original source