Is it possible to write a function work for int and long (float, byte .etc) in F#?

StackOverflow https://stackoverflow.com/questions/21977065

  •  15-10-2022
  •  | 
  •  

Domanda

when use

let add a b = a + b

it works for int. and

let add2 a b:float = a + b

work for float.

Is it possible to write a function work for int and long (float, byte .etc) in F#?

i need a function whose "a" work for int and long like this:

let f a b = a >>> b 
let f (a:int64) b = a >>> b

is it possible in F#?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top