I want to use functions from a module inside the file BasicFunctions.fs. After completing f# hello world tutorial one next step is to work through F# Tour.
The question what is the equivalent of import in F# and printfn an integer helped a bit. The question value or constructor not defined seem to be not relevant for my case.
Attempt 1: change config to include second file
If i change my project configuration myFsharpApp.fsproj
to this
<ItemGroup>
<Compile Include="BasicFunctions.fs" />
<Compile Include="Program.fs" />
</ItemGroup>
I get the error: FSC : error FS0225: Source file 'C:\dev\fsharp\myFSharpApp\BasicFunctions.fs' could not be found [C:\dev\fsharp\myFSharpApp\myFSharpApp.fsproj]
But the file BasicFunctions.fs can be found under the path 'C:\dev\fsharp\myFSharpApp\BasicFunctions.fs'. So i do not understand why it is not found.
Attempt 2: change the config to this:
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
Using dotnet build
then returns
- error FS0039: The namespace or module 'BasicFunctions' is not defined
- error FS0001: Type mismatch. Expecting a ''a -> 'b -> 'c' but given a ''a -> unit ' The type ''a -> 'b' does not match the type 'unit'
- error FS0039: The value or constructor 'sampleFunction1' is not defined.[C:\dev\fsharp\myFSharpApp\myFSharpApp.fsproj]
Most of the code is copied from the F# Tour. The difference is that i want to import functions from the file BasicFunctions.fs
and want to print the result of sampleFunction1 x = x*x + 3
The code structure is the following
// BasicFunctions.fs
module BasicFunctions =
let sampleFunction1 x = x*x + 3
// Program.fs
module main =
open BasicFunctions
// Define a new function to print a name.
let printGreeting name =
printfn "Hello %s from F#!" name
[<EntryPoint>]
let main argv =
printfn "%d" BasicFunctions.sampleFunction1 3 // 12 expected
0 // return an integer exit code
Questions
- What am i doing wrong in importing another file and its functions?
- What is wrong with
sampleFunction1 x = x*x + 3
? - Why is
printfn "%d" 12
not working assuming thatsampleFunction1
returns an int with the value 12?
Screen of current code state
Content of fsproj
This is the content of myFSharpApp.fsproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
</Project>