1

您好我正在尝试扩展 seq.groupby 函数。在一个单一的论点上,这是可行的,并且在此处之前已在此处讨论过,关键代码重复:

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

我想做同样的事情,但有多个分组参数。这是我尝试过的:

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

这个 groupby 多个项目似乎不起作用。我知道在 c# 中我会这样做:

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

我怎样才能在 Fsharp 中做到这一点?

4

1 回答 1

3

像这样:

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
于 2013-10-02T14:09:53.120 回答