【问题标题】:F# not returning at end of expressionF# 未在表达式末尾返回
【发布时间】:2019-10-15 03:21:56
【问题描述】:

我遇到一个问题,即 F# 程序没有在表达式末尾返回并最终执行它下面的下一个表达式。

文件中出现的两个表达式:

   let startCycle = 
        printfn "startCycle"
        (0, "")


   let blah = 
        printfn "blah"
        (0, "")

startCycle 被调用时,它会将两条消息都打印到控制台。使用调试器单步执行它从第一个(0, "")printfn "blah" 并在遇到第二个(0,"") 时返回。我已经检查了几次间距,Visual Studio 似乎将它们识别为两个单独的表达式。

另一个奇怪的事情是,如果我多次调用startCycle,它只会在第一次打印,之后的每次调用都不会打印到控制台,除非我停止并重新启动应用程序。我将 F# 4.7 与 .NET Core 3 一起使用。我缺少什么?

编辑: 如果有帮助,下面是 startCycle 的调用方式:

    let Run (cmdline: string) : (int * string) =
        let cmodel = parseCmd cmdline
        printfn "%A" cmodel
        match cmodel.Command with
        | "sendMsg4" -> Commands.sendMsg4 cmodel.Args
        | "sendMsg7" -> Commands.sendMsg7 cmodel.Args
        | "sendMsg8" -> Commands.sendMsg8 cmodel.Args
        | "sendMsg10" -> Commands.sendMsg10 cmodel.Args
        | "sendMsg16" -> Commands.sendMsg16 cmodel.Args
        | "sendMsg19" -> Commands.sendMsg19 cmodel.Args
        | "sendMsg22" -> Commands.sendMsg22 cmodel.Args
        | "sendMsg29" -> Commands.sendMsg29 cmodel.Args
        | "sendMixMessages1929" -> Commands.sendMixMessages1929
        | "help" | "Help" -> Commands.help cmodel.Args
        | "startCycle" -> Commands.startCycle
        | "stopCycle" -> Commands.stopCycle
        | "cycleStatus" -> Commands.cycleStatus
        | "set" -> Commands.setStateValue cmodel.Args
        | "show" -> Commands.show cmodel.Args
        | "" -> (1, "")
        | _ -> (-1, "Unknown Command")

【问题讨论】:

  • 你能显示整个源文件吗?如果startCycleblah 只是需要执行副作用来评估的变量,那么触发printfn 表达式是有道理的。
  • 所有非函数且处于模块级别的 let 绑定在访问该模块的任何值或函数时执行一次且仅执行一次。您的 let 绑定属于此类别。

标签: .net-core f#


【解决方案1】:

startCycleblah 不是写成函数,而是写成普通值。 F# 中的 let 关键字用于两者。不用担心,对于刚接触该语言的人来说,这是一个非常常见的混淆来源。

要创建一个不带参数的函数,您需要放入unit 的“虚拟”参数,写为()

let startCycle () =
    printfn "startCycle"
    (0, "")

然后这样调用:Commands.startCycle ()

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多