If you want both a
and b
to be of type float * float
, you can just straight up specify that:
let add (a : float * float) (b : float * float) = ...
Or you can destructure the tuples right in the parameter declarations:
let add (a1:float, a2:float) (b1:float, b2:float) =
(a1 + b1), (a2 + b2)
Incidentally, you only have to specify type of one of the tuples, the other one will be inferred from the fact that it's elements are added to those of the first tuple:
let add (a1:float, a2:float) (b1, b2) =
(a1 + b1), (a2 + b2)
Alternatively, you can mark the function inline
:
let inline add a b = ...
This will mean that the function doesn't get compiled into IL, but instead gets expanded at every use site. This, in turn, will make it able to work with any type that has the +
operator.
A non-inline
function, which gets compiled to IL, cannot do that, because IL does not allow to specify a constraint like "has a +
operator". But the compiler has to use some type, so it defaults to int
.
Even more alternatively, you can prevent the compiler from defaulting to int
by giving it some other source to infer the types from. For example, a use site in the same file:
let add a b = ...
let x = add (1.0, 2.0) (3.0, 4.0)
The last line will let the compiler know that you expect the parameters to be float
.