Given a sequence of a group id/value tuples, it was easy to calculate group totals (pretty much the same way I would do it with C# and LINQ):
let items = [\"g1\"
Although I would use kvb's suggestion, if you're going to roll your own, I suggest using Dictionary
instead of Map
. In my testing it was at least 400% faster.
let groupBy f (list:list<_>) =
let dict = Dictionary()
for v in list do
let k = f v
match dict.TryGetValue(k) with
| true, l -> dict.[k] <- v :: l
| _ -> dict.Add(k, [v])
dict |> Seq.map (|KeyValue|) |> Seq.toList
Or:
let groupSumBy (list:list<_>) =
let dict = Dictionary()
for k, v in list do
match dict.TryGetValue(k) with
| true, n -> dict.[k] <- v + n
| _ -> dict.Add(k, v)
dict |> Seq.map (|KeyValue|) |> Seq.toList
By ref version:
let groupSumBy (list:list<_>) =
let dict = Dictionary()
let mutable n = 0
for k, v in list do
match dict.TryGetValue(k, &n) with
| true -> dict.[k] <- v + n
| false -> dict.Add(k, v)
dict |> Seq.map (|KeyValue|) |> Seq.toList