nik
nik

Reputation: 1784

Aggregation by multiple arguments and then arithmetic operation in F#

Hi I m trying to expand a seq.groupby function. On a single argument this works and was discussed here before here, key code repeated:

let group_fold key value fold acc seq =
seq |> Seq.groupBy key 
    |> Seq.map (fun (key, seq) -> (key, seq |> Seq.map value |> Seq.fold fold acc))


let tuples = [("A",12); ("A",10); ("B",1);  ("C",2); ("C",1)]

let regular = group_fold fst snd (+) 0 tuples 
let piped = tuples  |> group_fold fst snd (+) 0

I would like to do the same but with multiple grouping arguments. This is what I tried:

let tuples = [("A", "B", "C", 12); ("A", "B", "C", 10); ("B","B","B",1);  ("C","B","B",2); ("C","B","B", 1)]

let group_fold key1 key2 key3 value fold acc seq =
    seq |> Seq.groupBy (key1 & key2 & key3) 
        |> Seq.map (fun (key1, key2, key3, seq) -> (key1, key2, key3, seq |> Seq.map value |> Seq.fold fold acc))

let piped = tuples  |> group_fold fst snd trd fth (+) 0

This groupby multiple items does not seem to work. i know in c# I would do sth like this:

tuples.GroupBy(a => new { a.fst, a.snd, a.trd})

How can I do this in Fsharp?

Upvotes: 1

Views: 144

Answers (1)

Daniel
Daniel

Reputation: 47914

Like this:

let group_fold keys value fold acc seq =
    seq |> Seq.groupBy keys 
        |> Seq.map (fun ((key1, key2, key3), seq) -> 
            (key1, key2, key3, seq |> Seq.map value |> Seq.fold fold acc))

let piped = tuples  |> group_fold (fun (k1, k2, k3, _) -> 
    k1, k2, k3) (fun (_, _, _, v) -> v) (+) 0

Upvotes: 3

Related Questions