2

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?

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
TK.
  • 46,577
  • 46
  • 119
  • 147

2 Answers2

5

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.

Community
  • 1
  • 1
Rustam
  • 1,766
  • 18
  • 34
4
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/

Grzegorz Sławecki
  • 1,727
  • 14
  • 27