#if - #else - #endif 破坏 F# 脚本

Mat*_*ein 2 f# f#-interactive f#-scripting f#-4.0

使用 Visual Studio 2015 Update 3 和fsi.exeF# v4.0,我尝试运行此脚本:

//error.fsx

#if INTERACTIVE
    let msg = "Interactive"
#else
    let msg = "Not Interactive"
#endif

let add x y =
    x + y

printfn "%d" (add 1 2)
Run Code Online (Sandbox Code Playgroud)

输出: error.fsx(12,15):错误 FS0039:未定义值或构造函数“add”

如果我然后注释掉#if- #else-#endif块,它工作正常:

// fixed.fsx

//#if INTERACTIVE
//    let msg = "Interactive"
//#else
//    let msg = "Not Interactive"
//#endif

let add x y =
    x + y

printfn "%d" (add 1 2)
Run Code Online (Sandbox Code Playgroud)

输出: 3

我确定我做错了什么(而不是这是一个错误),但我一生都无法弄清楚如何进行这项工作。

想法?

Tom*_*cek 5

这是由缩进引起的let msg。以下工作正常:

#if INTERACTIVE
let msg = "Interactive"
#else
let msg = "Not Interactive"
#endif

let add x y =
    x + y

printfn "%d" (add 1 2)
Run Code Online (Sandbox Code Playgroud)

我不得不说,我不完全确定为什么代码给出了你提到的错误信息——我怀疑这是错误报告中的一个错误,值得向 F# 团队报告。至少,应该有一个合理的错误信息!

似乎有了缩进,F#解析器实际上是这样解析代码的:

let msg = "Interactive"
let add x y =
  x + y 
    printfn "%d" (add 1 2)
Run Code Online (Sandbox Code Playgroud)

之前的间距也会let msg导致编译器将其printfn视为缩进。如果您y使用工具提示查看编辑器中变量的类型,您会发现情况就是这样...

  • 哇,你快马蒂亚斯!我刚刚创建了一个 Disqus 帐户,所以我可以直接在你的博客上告诉你! (2认同)