2013-10-08 22 views
1

enter image description here如何在F#中实现读表函数? (如Vlookup)

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

(在网站试试F#,学习 - >金融建模 - >使用Yahoo Finance Type Provider 它建议我们使用Samples.Csv.dll。但是我没有安装它,也不想安装它包只是一个功能:(..)


我跟着教程(http://fsharp.github.io/FSharp.Data/library/CsvProvider.html) 并试图在我的计算机上运行程序。但我有麻烦了

enter image description here

它无法识别CsvProvider类型(所以我不能使用Stocks.Load函数。)

问题是什么......?

+0

您是否要求一个从F#到Excel的功能? –

+2

数据的来源是什么?如果您从CSV获取数据,请查看http://fsharp.github.io/FSharp.Data/library/CsvProvider.html和http://fsharp.github.io/FSharp.Data/library /CsvFile.html。这些基本上是Try F#中可用的CSV工具的更高级版本。 –

+0

我想从csv文件读取数据到F#。 –

回答

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上使用)。

4

这是代码在F#数据中使用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