f# idiomatic type resolution solution for resolving to the wrong type

122 Views Asked by At

I'm just getting started with F# but I have some code that is analogous to the following:

let square x = x*x

let result = square 5.1

let result' = square 12

Unfortunately, this results in the following error: This expression was expected to have type float but here has type int

Is there an idiomatic F# solution to this problem, or is my thinking being tainted by my C# experience?

2

There are 2 best solutions below

0
On BEST ANSWER

Just write it like that:

let inline square x = x * x

Otherwise, after first time you used that square function, it type was inferred to be float -> float. Hence, and given that F# does not do automatic conversion from int to float, you receive an error.

So, if you don't want to use inline, the simplest solution is to write

 let result' = square (float 12)

It is simple and yet readable.

For more advanced solutions please take a look at this: Does F# have generic arithmetic support?

But those solutions are (imho) incomprehensible.

0
On
let inline square x = x * x

let result = square 5.1

let result' = square 12

printfn "%f" result
printfn "%d" result'

There's a whole article by Tomas Petricek on this subject: http://tomasp.net/blog/fsharp-generic-numeric.aspx/