[英]How to write a csv in F#?
How would I write a record in F# into a csv? 如何将F#中的记录写入csv? It would be optimal to have one row for each instance of a certain variable. 对于某个变量的每个实例,最好有一行。 My record and final output is a map like the one below. 我的记录和最终输出是如下所示的地图。
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 EDITED
This is what I have tried, but I am getting the error that (A,B,C,D,E,F) are not defined
, and that it is recommended that I use the syntax new (type) args
. 这是我试过的,但我得到的错误是(A,B,C,D,E,F) are not defined
,并且it is recommended that I use the syntax new (type) args
。 This last error is showing up under >> MyCsvType
最后一个错误显示在>> 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()
Your code is almost there, except that the myCsvBuildRow
function needs to access members of the Family
type using their correct names. 您的代码几乎就在那里,除了myCsvBuildRow
函数需要使用正确的名称访问Family
类型的成员。 In your version, you are accessing names such as A
, B
, etc., but those are the names of columns in your CSV file, not the names of members of the F# record. 在您的版本中,您正在访问A
, B
等名称,但这些名称是CSV文件中的列名,而不是F#记录成员的名称。 The following does the trick for me: 以下是我的诀窍:
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.