如何在F#中实现读表功能? (像Vlookup)

时间:2013-10-08 13:46:55

标签: f# vlookup

enter image description here

我需要一个功能。 当我输入0~15和保护时,它将返回45%。 就像Excel中的Vlookup功能一样。 F#中有这样的函数吗?

(在网站上试用F#,学习 - >财务建模 - >使用雅虎财务类型提供商 它建议我们使用Samples.Csv.dll。但是,我无法安装它,并且不想仅为函数安装该包:( ..)


我按照教程(http://fsharp.github.io/FSharp.Data/library/CsvProvider.html) 并试图在我的电脑上运行该程序。但我现在遇到了麻烦

enter image description here

无法识别CsvProvider类型(因此我无法使用Stocks.Load函数。)

问题是什么?

2 个答案:

答案 0 :(得分:4)

这是在F#Data中使用CSV type provider时代码的外观。要使其生效,您需要添加对FSharp.Data.dll的引用。最好的方法是从NuGet安装软件包。在Visual Studio中,它将为您添加引用,在命令行中您可以说:

nuget install FSharp.Data

或者,如果您在F#脚本文件中,则需要安装nuget包,然后添加#r @"C:\path\to\FSharp.Data.dll"。然后你可以写下面的内容:

open FSharp.Data
// Generate type based on a local copy with sample data
type Data = CsvProvider<"sample.csv">
// Load actual data from a file (this can be a different file with the same structure)
let loaded = Data.Load("runtime/file/name.csv")

// Find row for a specified age range & look at the properties
let row = loaded.Data |> Seq.find (fun r -> r.Age = "0~15")
row.Protection
row.Saving
row.Specified

答案 1 :(得分:2)

执行此操作的一种非常简单的方法是使用DataTable

open System.Data
open System.IO
open LumenWorks.Framework.IO.Csv

let vlookup =
  let table = new DataTable()
  do
    use streamReader = new StreamReader(@"C:\data.csv")
    use csvReader = new CsvReader(streamReader, hasHeaders=true)
    table.Load(csvReader)
    table.PrimaryKey <- [|table.Columns.["Age"]|]
  fun age (column: string) -> table.Rows.Find([|age|]).[column]

//Usage
vlookup "0~15" "Protection" |> printfn "%A"

那里不乏CSV阅读器。我使用了this especially fast one(也可以在NuGet上使用)。