Why do F# functions evaluate before they are called?

蹲街弑〆低调 提交于 2019-11-28 06:06:21

问题


If I define a module as such:

module Module1
open System

let foo =
    Console.WriteLine("bar")

Then, in interactive do

#load "Library1.fs" //where the module is defined
open Module1

I see a

[Loading c:\users\jj\documents\visual studio 2015\Projects\Library1\Library1\Library1.fs] bar

Indicating that the foo function ran without me even calling it!

How/why does this happen? Is there any way to prevent it?

I'm aware that the return value of foo is whatever (Console.Writeline("bar")) evaluates to, and that there isn't any reason that can't be evaluated "immediately?" (when the module is loaded I guess?) - but is there a way to prevent it from happening? If my module functions alter the state of some other stuff, can I ensure that they do not evaluate until called?


回答1:


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 ().




回答2:


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.



来源:https://stackoverflow.com/questions/32855383/why-do-f-functions-evaluate-before-they-are-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!