In C# I can define an extension method that applies only to parameterized generic types:
public static bool fun(this List<int> coll, int x)
{
return coll.Contains(x);
}
I tried the same in F# but found no way to do so:
type List<'k when 'k :> int32> with
member o.x s = o.Contains s
This raises Error FS0660: This code is less generic than required by its annotations because the explicit type variable 'k' could not be generalized. It was constrained to be 'int32'.
It certainly is possible to define a generic extension method like
type List<'k> with
member o.x s = o.Contains s
and on a side note to make that extension method available in C#. But that is not the question here. i am concerned about a parameterized generic function. Which I believe is possible to declare only in C# but not in F#.
I conclude that in C# extension methods are functions while in F# the similar concept is implemented as type extensions and parameterized generics are no types, so this is not possible.
Am I correct that there is no way to do the same in F#?
There is a similar question here: Is it possible to define a generic extension method in F#? but since 11 years have passed I raise the topic again.
CodePudding user response:
F# has a mechanism for defining extensions that is "C#-compatible", and your use case is specifically called out, check here.
Something like this should work:
open System.Collections.Generic
open System.Runtime.CompilerServices
[<Extension>]
type Extensions =
[<Extension>]
static member inline ContainsTest(xs: List<int>, s: int) =
xs.Contains(s)