当我尝试控制台编程时,我收到了意想不到的结果。
open System
let printSomeMessage =
printfn "Is this the F# BUG?"
[<EntryPoint>]
let main args =
if args.Length = 2 then
printSomeMessage
else
printfn "Args.Length is not two."
0
printSomeMessage函数包含在.cctor()函数中。这是IL DASM的结果。
.method private specialname rtspecialname static
void .cctor() cil managed
{
// Code size 24 (0x18)
.maxstack 4
IL_0000: nop
IL_0001: ldstr "Is this the F# BUG\?"
IL_0006: newobj instance void class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`5<class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [mscorlib]System.IO.TextWriter,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [FSharp.Core]Microsoft.FSharp.Core.Unit>::.ctor(string)
IL_000b: call !!0 [FSharp.Core]Microsoft.FSharp.Core.ExtraTopLevelOperators::PrintFormatLine<class [FSharp.Core]Microsoft.FSharp.Core.Unit>(class [FSharp.Core]Microsoft.FSharp.Core.PrintfFormat`4<!!0,class [mscorlib]System.IO.TextWriter,class [FSharp.Core]Microsoft.FSharp.Core.Unit,class [FSharp.Core]Microsoft.FSharp.Core.Unit>)
IL_0010: dup
IL_0011: stsfld class [FSharp.Core]Microsoft.FSharp.Core.Unit '<StartupCode$FSharpBugTest>'.$Program::printSomeMessage@3
IL_0016: pop
IL_0017: ret
} // end of method $Program::.cctor
所以,它的执行结果是这样的。
Is this the F# BUG?
Args.Length is not two.
我错过了一些语法或F#特征吗?还是F#builder的BUG?
答案 0 :(得分:10)
不,这是您的代码中的错误。您需要在“printSomeMessage”之后添加括号,否则printSomeMessage是一个简单的值而不是函数。
open System
let printSomeMessage() =
printfn "Is this the F# BUG?"
[<EntryPoint>]
let main args =
if args.Length = 2 then
printSomeMessage()
else
printfn "Args.Length is not two."
0
在模块的构造函数中初始化简单值,因此您可以看到在初始化模块时调用代码。当您考虑它时,这是合乎逻辑的,简单值的正常情况是将字符串,整数或其他字面值绑定到标识符。你会期望这是一个启动。即,以下内容将在模块启动时受到约束:
let x = 1
let y = "my string"