我已经为F#中的某些客户端数据定义了一种记录类型,如下所示:

  type DataPoint = {
       date: string;
       dr: string;
       Group: string;
       Product: string;
       Book: int;
       Revenue: int} with
          static member fromFile file =
               file
               |> File.ReadLines
               |> Seq.skip 1 //skip the header
               |> Seq.map (fun s-> s.Split ',') // split each line into array
               |> Seq.map (fun a -> {date = string a.[0]; dr = string a.[1];
                              Group = string a.[2]; Product = string a.[3];
                                Book = int a.[4]; Revenue = int a.[5] });;

    // creates a record for each line
    let pivot (file) = DataPoint.fromFile file
              |> ??????????

对于日期,dr,Group和Product都相等的行,我想对所有Book和Revenue条目求和,以产生一个透视表行。因此,某种if if语句应该没问题。我怀疑我需要从第一个数据点开始,递归地添加每个匹配的行,然后删除匹配的行,以避免输出重复。

完成此操作后,我将能够轻松地将这些数据透视表的行写入另一个csv文件。

谁能让我入门?

最佳答案

您需要的是Seq.groupBySeq.reduce:

let pivot file =
    DataPoint.fromFile file
    |> Seq.groupBy (fun dp -> dp.date, dp.dr, dp.Group, dp.Product)
    |> Seq.map (snd >> Seq.reduce (fun acc dp ->
                          { date = acc.date; dr = acc.dr;
                            Group = acc.Group; Product = acc.Product;
                            Book = acc.Book + dp.Book;
                            Revenue = acc.Revenue + dp.Revenue; }))

关于f# - F#中的条件总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13474223/

10-09 08:54
查看更多