【问题标题】:#if - #else - #endif breaking F# Script#if - #else - #endif 破坏 F# 脚本
【发布时间】:2016-09-19 20:14:20
【问题描述】:

使用来自 F# v4.0 的 Visual Studio 2015 Update 3 和 fsi.exe 我正在尝试运行此脚本:

//error.fsx

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

let add x y =
    x + y

printfn "%d" (add 1 2)

输出: error.fsx(12,15): error FS0039: The value or constructor 'add' is not defined

如果我随后注释掉 #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)

输出: 3

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

想法?

【问题讨论】:

    标签: f# f#-interactive f#-scripting f#-4.0


    【解决方案1】:

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

    #if INTERACTIVE
    let msg = "Interactive"
    #else
    let msg = "Not Interactive"
    #endif
    
    let add x y =
        x + y
    
    printfn "%d" (add 1 2)
    

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

    貌似有了缩进,F#解析器实际上解析代码如下:

    let msg = "Interactive"
    let add x y =
      x + y 
        printfn "%d" (add 1 2)
    

    let msg 之前的空格导致编译器也将printfn 视为缩进。如果您使用工具提示在编辑器中查看y 变量的类型,您会看到这种情况...

    【讨论】:

    • 谢谢托马斯!一旦你指出它是有道理的。我从here (#3) 中获取了示例代码,并假设它可以正常工作。非常感谢!
    • 这是一个有趣的错误 - 我花了更多时间弄清楚发生了什么,我认为这是一个错误(至少在错误报告中)。
    • 马特克莱恩:对不起!我会修复帖子,可能有些格式在那里被破坏了。
    • 哇,你的马蒂亚斯真快!我刚刚创建了一个 Disqus 帐户,所以我可以直接在你的博客上告诉你!
    • 再次感谢@TomasPetricek!我已将此问题提交给 F# 团队 here
    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多