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",5; "g2",10; "g1",20]
let groupsums =
items
|> Seq.groupBy (fun x -> fst x)
|> Seq.map (fun (g, s) -> Seq.fold (fun acc x -> acc + snd x) 0 s)
But being new to F#, I can’t see a way to so the same with lists. Do I have to use mutable variables, or is there a functional way to do the same with lists?
There is no built in
List.groupBy. A number of F# built in types have functions that are assigned the seq version of said function. e.g. fromlist.fslet inline sumBy f (list : list<_>) = Seq.sumBy f listI’m pretty sure the designers of F# had many discussions about what to duplicate for the sake of consistency and what to omit for for sake of DRY. I personally wish they stuck with DRY.
If you want to make your own “functional” List.groupBy I’d use map and list.
You can skip keeping lists if you only need the sum.
Output