CoderLee
CoderLee

Reputation: 3479

How to interpolate an int into a string with F#?

I'm trying what should be a really basic example application, but this particular example from MS's F# intro produces this warning in intellisense:

Type mismatch. Expecting a
    ''a -> int'    
but given a
    ''a -> unit'    
The type 'int' does not match the type 'uint'F# Compiler1

from this code: (fwiw I have tried both implicit and explicit typing for sum)

open System

[<EntryPoint>]
let main argv =
    printfn "Welcome to the calculator program"
    printfn "Type the first number"
    let firstNo = Console.ReadLine()
    printfn "Type the second number"
    let secondNo = Console.ReadLine()
    printfn "First %s, Second %s" firstNo secondNo
    let sum: int = 0
    printfn "The sum is %i" sum

Then when I compile I get this error, as expected, based off the warning:

error FS0001: Type mismatch. Expecting a↔    ''a -> int'    ↔but given a↔    ''a -> unit'    ↔The type 'int' does not match the type 'unit' [C:\Users\user-name\source\repos\MyFSharpApp\MyFSharpApp.fsproj]

Being new to F# I'm not sure why the printfn function thinks an int is a unit and breaking compilation. Could really use an explanation and/or link(s) to doc(s) of why this is the case and how to resolve it.


Edit

So an interesting point, even when I remove the interpolation all together and just print a string, I get the same error. So no int at all, but the string expects an int instead of a unit...but, why? I'm guessing I have some sort of syntax error, regardless this seems quite weird.

Upvotes: 2

Views: 98

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

The main function is supposed to return an int, which will become the program execution result. The convention is: zero for success, non-zero to signify an error code (this is not F#-specific).

When you create a new project with dotnet new, as the exercises direct, the main function is generated returning a zero.

But as you have confirmed in the comments, your main function does not currently have a zero, which probably means that you have deleted it accidentally.

Just add the zero back in and the error will go away.


In the shiny new .NET 6, the default generator generates an implicit entry point instead of the good ol' main function, in which case the return value is not required, and if you do want to return one, you have to use the exit function.

However, this clearly does not apply to the current question, since the OP's generator generated a main function, not implicit entry point.

Upvotes: 5

Related Questions