When you want to write a function that can work with multiple different numeric types, you need to use inline
and "static member constraints". The problem is that normal .NET generics cannot capture constraints like "supports the + operator".
To make your sample add
function generic, you can use inline
:
let inline add x y = x + y
When you look at the inferred type, you'll see something like this:
val inline add :
x: ^a -> y: ^b -> ^c
when ( ^a or ^b) : (static member ( + ) : ^a * ^b -> ^c)
This essentially says that the function can be called on any two arguments that support the +
operator. Note that this only works because the function is inline
and so the F# compiler does not have to rely on .NET to express the constraints. The same works for the >>>
operator:
let inline f a b = a >>> b
The function can now be used with both int64
and int
arguments:
f 1024L 2
f 1024 2
I wrote an article about writing generic numeric code in F# some time ago which you may find useful too.