Module initialize

module Test
printfn "hello"

Why if it module load in fsx
in console will be printed message, but in fspro if open module it does not?
In most languages with modules if we uses module it always init. for example Визуальные интерактивные модели для образования и науки / Ви́жуал СФУ / Оберон Онлайн (oberon.org)

From what I can tell, it has to actually use something from the module for it to do the init. It’s not enough to just open it.
If you do

module Test
printfn "hello"
let finishTxt = "do" + "ne"

and then in Program.fs do

open Test
printfn "%s" finishTxt

then you will see “hello” printed out. Interestingly, if you define
let finishTxt = "done"
then you won’t see “hello” printed out, presumably because it just inlined finishTxt as a literal value without actually evaluating anything in the module.

You can count on any initialization at the top of a module being run before any of the contents of the module, but I would recommend against trying to otherwise control exactly when any initialization runs (e.g., by the order of open statements). I think the F# compiler sort of decides when exactly the initialization of a module gets run.

1 Like

AFAIK, an F# module maps to a .NET Class. The Class has a static constructor, and those are only run the first time the class is instantiated, or a static method is called (which is what finishTxt becomes, a static method of a Class).

So, this is a .NET thing and not an F# thing. C# and VB and C++/CLI would get the same behavior for any .NET classes.

If you want to learn about the details of F# static initialization, check §12.5.1 of the F# 4.1 spec. (Details may have changed in later language versions).