Topazus
Topazus

Reputation: 9

How to correctly call a function of a module in a file that includes mutiple modules in F#

After reading F# moudles doc, I am still obfuscated by the use of modules.

MyTest.fs file

module MyTest

module MyModule1 =
    let f =
        // thread sleep
        printfn "hi from module 1"

module MyModule2 =
    let f =
        printfn "hi from module 2"

Program.fs file

// entry point
[<EntryPoint>]
let main argv =
    MyTest.MyModule2.f
    0

I want to only use function named f in MyModule2. When I use dotnet run from the project, the output is different from what I thought, which the output I thought may be hi from module 2.

$ dotnet run
hi from module 1
hi from module 2

Upvotes: 0

Views: 24

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80915

Those f things are not functions, but values. They get initialized at program start, and the way they're initialized, as you wrote it, is by calling printfn and assuming its return value.

To make them functions, give them parameters:

module MyModule1 =
    let f x =
        // thread sleep
        printfn "hi from module 1"

module MyModule2 =
    let f x =
        printfn "hi from module 2"

// entry point
[<EntryPoint>]
let main argv =
    MyTest.MyModule2.f 42
    0

Since you don't actually do anything with parameters, a better style is to use parameters of type unit, which has only one possible value, and that value is denoted ():

module MyModule1 =
    let f () =
        // thread sleep
        printfn "hi from module 1"

module MyModule2 =
    let f () =
        printfn "hi from module 2"

// entry point
[<EntryPoint>]
let main argv =
    MyTest.MyModule2.f ()
    0

Upvotes: 1

Related Questions