是否可以在 F# 中为参数化泛型类型定义扩展方法(就像在 C# 中一样)

cit*_*kid 2 generics extension-methods f#

在 C# 中,我可以定义一个仅适用于参数化泛型类型的扩展方法:

public static bool fun(this List<int> coll, int x)
{
    return coll.Contains(x);
}
Run Code Online (Sandbox Code Playgroud)

我在 F# 中尝试了相同的操作,但发现没有办法这样做:

type List<'k when 'k :> int32> with
    member o.x s = o.Contains s
Run Code Online (Sandbox Code Playgroud)

这会引发错误 FS0660:此代码的通用性低于其注释的要求,因为无法泛化显式类型变量“k”。它被限制为“int32”。

当然可以定义一个通用的扩展方法,例如

type List<'k> with
    member o.x s = o.Contains s
Run Code Online (Sandbox Code Playgroud)

并附注使该扩展方法在 C# 中可用。但这不是这里的问题。我担心参数化通用函数。我认为只能在 C# 中声明,但不能在 F# 中声明。

我的结论是,在 C# 中,扩展方法是函数,而在 F# 中,类似的概念是作为类型扩展实现的,而参数化泛型不是类型,因此这是不可能的。

我是否正确,在 F# 中没有办法做同样的事情?

这里有一个类似的问题:Is it possible to Define a generic extension method in F#? 但11年过去了,我又提起这个话题。

scr*_*wtp 6

F# 有一种定义“C# 兼容”扩展的机制,并且您的用例已明确指出,请在此处查看。

像这样的东西应该有效:

open System.Collections.Generic
open System.Runtime.CompilerServices

[<Extension>]
type Extensions =
    [<Extension>]
    static member inline ContainsTest(xs: List<int>, s: int) = 
        xs.Contains(s)
Run Code Online (Sandbox Code Playgroud)