Why do F# functions evaluate before they are called?

前端 未结 2 942
一个人的身影
一个人的身影 2020-12-20 00:25

If I define a module as such:

module Module1
open System

let foo =
    Console.WriteLine(\"bar\")

Then, in interactive do

         


        
相关标签:
2条回答
  • 2020-12-20 01:01

    I believe let foo = x is essentially a static value that gets evaluated immediately, once. If you want a parameterless function, you would need let foo () = Console.WriteLine("bar"), using it as foo ().

    If you don't want to have to use the parentheses when calling, something like type Test () = static member foo with get () = System.Console.WriteLine("bar"), using it as Test.foo should work.

    0 讨论(0)
  • 2020-12-20 01:08

    Function bodies are evaluated when the function is called, just as you want. Your problem is that foo is not a function, it's a variable.

    To make foo a function, you need to give it parameters. Since there are no meaningful parameters to give it, the unit value (()) would be the conventional parameter:

    let foo () =
        Console.WriteLine("bar")
    

    Accordingly a call of this function would look like foo ().

    0 讨论(0)
提交回复
热议问题