[英]How to write a csv in F#?
如何将F#中的记录写入csv? 对于某个变量的每个实例,最好有一行。 我的记录和最终输出是如下所示的地图。
type Family =
{ Month : int
Year : int
Income : float
Family : int
Dogs : int
Cats : int
}
let monthly =
timeMap
|> Seq.ofList
|> Seq.map(fun ((month,year), rows) ->
{ Month = month
Year = year
Income = rows.Inc
Family = familyMap.[(month,year)].Children
Dogs = familyMap.[(month,year)].Dogs
Cats = familyMap.[(month,year)].Cats
})
|> List.ofSeq
let map =
monthly
|> List.map (fun x -> (x.Year,x.Month),x)
|> Map.ofList
EDITED
这是我试过的,但我得到的错误是(A,B,C,D,E,F) are not defined
,并且it is recommended that I use the syntax new (type) args
。 最后一个错误显示在>> MyCsvType
type MyCsvType = CsvProvider<Schema = "A (int), B (int), C (float), D (int), E (int), F (int)", HasHeaders = false>
let myCsvBuildRow (x:Family) = MyCsvType.Row(x.A,x.B,x.C,x.D,x.E,x.F)
let myCsvBuildTable = (Seq.map myCsvBuildRow) >> Seq.toList >> MyCsvType
let myCsv = monthly|> myCsvBuildTable
myCsv.SaveToString()
您的代码几乎就在那里,除了myCsvBuildRow
函数需要使用正确的名称访问Family
类型的成员。 在您的版本中,您正在访问A
, B
等名称,但这些名称是CSV文件中的列名,而不是F#记录成员的名称。 以下是我的诀窍:
type MyCsvType = CsvProvider<Schema = "A (int), B (int), C (float), D (int), E (int), F (int)", HasHeaders = false>
let myCsvBuildRow (x:Family) =
MyCsvType.Row(x.Month,x.Year,x.Income,x.Family,x.Dogs,x.Cats)
let myCsvBuildTable data =
new MyCsvType(Seq.map myCsvBuildRow data)
let myCsv = family |> myCsvBuildTable
myCsv.SaveToString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.