问题描述
我尝试按照以下示例使用来自FSharp.Data的CsvProvider:http://fsharp.github.io/FSharp.Data/library/CsvProvider.html
在示例中,他们定义了一个类型,然后使用该类型,但看起来他们是在交互模式下进行的。我正在尝试在主体中做同样的事情,但是我不明白为什么它不起作用。
在示例中,他们执行以下操作:
next
这是我的尝试
type Stocks = CsvProvider<"../data/MSFT.csv">
尝试定义urls变量时遇到一些语法错误。为什么会这样呢?我是F#的新手,所以对新手的解释会更多。
谢谢。
解决方法
这里发生了一些事情:
-
您无法在函数内定义类型,因此需要将
urls
的定义移出main
函数,并移入模块或命名空间。 -
类型提供程序为您提供了一种生成类型的简便方法,而不是您自己手动定义它们,但是仍需要在编译时生成这些类型。这意味着您传递给类型提供程序的任何参数都必须是静态的,即在编译时必须有一个值。
对于您而言,示例CSV文件的
filePath
是您传递给CsvProvider
的唯一参数,但是由于此值是从命令行参数派生的,因此仅在运行。要将静态文件名传递给CsvProvider
,您可以使用文字字符串,例如// Option 1: Use an inline literal string,like in the example from FSharp.Data. type Urls = CsvProvider<"test.csv">
// Option 2: Use a named literal so that the compiler knows this value is static. let [<Literal>] FilePath = "test.csv" type Urls = CsvProvider<FilePath>
-
这可能只是代码示例中的格式错误,但是为了从
0
函数返回main
,必须对其进行缩进,以便将其识别为最后一个表达式该代码块。
将所有内容放在一起可以得到以下内容:
open FSharp.Data
module Program =
// The `Urls` type is now defined within a module.
// This type is generated at compile-time from the sample file.
// Assumes the sample file 'test.csv' exists in the project folder at compile-time.
type Urls = CsvProvider<"test.csv">
[<EntryPoint>]
let main args =
// Use the generated `Urls` type to load some data at runtime.
let urls = Urls.Load("...")
// ...
// Return an integer exit code.
0