Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

module - Why do F# functions evaluate before they are called?

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:usersjjdocumentsvisual studio 2015ProjectsLibrary1Library1Library1.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...