F# CsvTypeProvider - 从推断类型映射函数

F# CsvTypeProvider - mapping function from inferred types

我正在使用 CsvTypeProvider 将 CSV 文件中的数据映射到我自己的数据结构中。这非常有效,除了我每次都必须重复映射函数:

type GamesFile = CsvProvider<"./data/15.csv">
let games15 = GamesFile.Load("./data/15.csv").Rows |> Seq.map ( fun c -> { Division = c.Div; Date = c.Date; HomeScore = c.HomeScore; AwayScore = c.AwayScore })
let games16 = GamesFile.Load("./data/16.csv").Rows |> Seq.map ( fun c -> { Division = c.Div; Date = c.Date; HomeScore = c.HomeScore; AwayScore = c.AwayScore })

当我尝试将它移动到一个函数时,我被告知 "Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved."

这是有道理的,但是当从 CSV 的内容推断类型时,我如何告诉映射函数它是什么类型?这个一般是怎么解决的?

类型提供程序生成一个表示该行的类型,并将其公开为主要提供类型的嵌套类型 - 在您的情况下别名为 GamesFile

这不是很明显,因为编辑器会显示类似
的工具提示 CsvFile<...>.Row 所以它不显示别名的名称,但它表明 Row 是一个嵌套类型。要在你的代码中使用类型,你可以只写 GamesFile.Row,所以你需要这样的东西:

type GamesFile = CsvProvider<"./data/15.csv">

let mapRows (rows:seq<GamesFile.Row>) = 
  rows |> Seq.map (fun c -> 
    { Division = c.Div; Date = c.Date; HomeScore = c.HomeScore; AwayScore = c.AwayScore })

let games15 = GamesFile.Load("./data/15.csv").Rows |> mapRows
let games16 = GamesFile.Load("./data/16.csv").Rows |> mapRows