Group totals in F# - easy with sequences, is it possible with lists?

后端 未结 3 1999

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\"         


        
3条回答
  •  野性不改
    2021-02-09 05:35

    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
    

提交回复
热议问题