考虑以下因素:
type Foo(bar:'a -> 'a list) =
member __.Bar = bar
我在参数列表中的第一个 'a
上收到警告:
This construct causes code to be less generic than indicated by the type annotations. The type variable 'a has been constrained to be type 'obj'.
为什么我会收到此警告?
在此特定示例中,是否可以有一个将任意类型的值转换为此类类型列表的成员,并通过构造函数提供该成员? (例如,可以想象 Foo
使用 List.replicate x
实例化,以获取用户选择的任何整数 x
。)
我不想让 Foo
本身变得通用,因为我有很多这样的参数和成员。
(我尝试这样做的原因是我想要某种结构,其中包含用户可重写的通用函数。)
最佳答案
即使您将 Foo
设为泛型,如果可以推断出泛型参数,您也无需在调用时显式提供泛型参数:
type Foo<'a>(bar:'a -> 'a list) =
member __.Bar = bar
Foo(fun x -> [x + 1])
我不确定这是否对您有帮助,但总的来说"Functions lose genericity when passed as values" .
关于generics - 具有构造函数提供的实现的通用成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46766906/