How to call a function in another source file?

I’m learning F#, and this question is so basic I have trouble crafting the right search query to learn the answer.

In short, how do I call a function from another source file? Here’s my attempt:

I’m working through the book Programming F# 3.0 but I’m on a Mac using dotnet core.

The book discusses modules and files being in a certain order, but file order isn’t a concept in .NET core apps, so far as I know. So I tried a few ways and failed to call a function from another source file.

Get Started with F# in Visual Studio Code | Microsoft Learn didn’t help either.

How do I call a function in another source file?

I’ve not been using F# myself for very long so hopefully this isn’t ‘the blind leading the blind’.

F# code cannot (under most circumstances) reference something that has not already been defined.

So, in this case, if the Square module is defined ‘after’ the Program.cs code then the Program.cs code cannot use the functions (and other things) in the Square module.
‘Before’ and ‘after’ is defined by the order in which the files are organised in the editor, or, I think, more specifically, in the .fsproj file (not the file system).

In Visual Studio (and I think Visual Studio Code) you can select a file and then use Alt+arrow-key to move a file up/down the list of files.

If you can’t do that then you can change the order by editing the .fsproj file and reordering the .fs files in one of the ItemGroup sections.
E.g.

<ItemGroup>
    <Compile Include="Square.fs" />
    <Compile Include="Program.fs" />
</ItemGroup>

(I noticed that Square.fs is missing from your .fsproj file, which may be the first problem to fix.)

Hopefully one of those things will get you up and running.

Note 1: In the Program.fs code, since you are opening the Square module, you don’t need to prefix the square function name with the name of the module.
Note 2: Your square function in the Square module doesn’t look right to me. let square x = x * x seems a better fit but I could be missing something.

Thank you GarryP! I updated my .csproj according to your instructions and it worked! And yes, there were syntax errors in my Square.fs which I fixed and pushed the new version to GitHub.

You’re welcome, and thanks for confirming that this was the solution.
It’s the first ‘fix’ that I’ve posted in these forums so it’s good to know that I’m getting a bit better at ‘this F# thing’.

It’s worth me noting that I tried using VS Code for a little while but found, amongst other issues, that the .fsproj file wasn’t being updated as I would have expected it to. It’s something which, I think, needs to be ‘kept an eye on’.

2 Likes