The type inference works so that your function sq
has type int -> int
, because the first time compiler sees you use that function, you pass it an integer. So it assumes that sq
is a function that takes an integer, and by definition of the function (x * x
) it also returns an integer.
It is a bit complicated to define a fully generic arithmetic function in F#, but one way to do it is to make the function inline
, like so:
let inline sq x = x * x
This way the body of your function will be inlined each time at the call site, so using an inlined sq
function will be the same as substituting it's body every time it's used.
This approach has it's drawbacks, and I think it will be interesting for you to see this question.