F# 类型推断不如类型注释指示的通用
F# type inference less generic than indicated by the type annotations
在以下代码片段的最后一行,我收到两个警告:This construct causes code to be less generic than indicated by the type annotations. The type variable 'c has been constrained to be type ''a'.
和 This construct causes code to be less generic than indicated by the type annotations. The type variable 'b has been constrained to be type ''a * 'a'.
type SomeBaseClass<'a> () =
class end
type SomeClass<'a when 'a:equality> (getValue:unit->'a, ?arg2:SomeBaseClass<'b>) =
inherit SomeBaseClass<'a*'a>()
member this.Value with get () = getValue ()
member this.Transform (transformation:'a->'c) =
let func ():'c = transformation this.Value
SomeClass<'c> (func, this) // warnings are attached to this line
另一方面,编译没有问题:
type SomeOtherClass<'a when 'a:equality> (getValue:unit->'a) =
inherit SomeBaseClass<'a*'a>()
member this.Value with get () = getValue ()
member this.Transform (transformation:'a->'c) =
let func ():'c = transformation this.Value
SomeOtherClass<'c> func
我没有看到任何阻止 transformation
返回与传递的类型不同的类型。我也不明白为什么第二个警告甚至是一个警告,因为显然我已经打算将新实例的 'b
类型参数设置为 'a*'a
.
我做错了什么?
泛型类型 SomeClass
在其构造函数中使用了泛型参数 'b
,但其定义中缺少该参数。将类型定义更改为
type SomeClass<'a, 'b when 'a:equality> ...
以及带有警告的行
SomeClass(func, this)
去除错误,返回的class类型为SomeClass<'c, ('a * 'a)>
.
虽然我不知道这是要达到什么目的,所以我无法判断这是否是一个明智的修正。
在以下代码片段的最后一行,我收到两个警告:This construct causes code to be less generic than indicated by the type annotations. The type variable 'c has been constrained to be type ''a'.
和 This construct causes code to be less generic than indicated by the type annotations. The type variable 'b has been constrained to be type ''a * 'a'.
type SomeBaseClass<'a> () =
class end
type SomeClass<'a when 'a:equality> (getValue:unit->'a, ?arg2:SomeBaseClass<'b>) =
inherit SomeBaseClass<'a*'a>()
member this.Value with get () = getValue ()
member this.Transform (transformation:'a->'c) =
let func ():'c = transformation this.Value
SomeClass<'c> (func, this) // warnings are attached to this line
另一方面,编译没有问题:
type SomeOtherClass<'a when 'a:equality> (getValue:unit->'a) =
inherit SomeBaseClass<'a*'a>()
member this.Value with get () = getValue ()
member this.Transform (transformation:'a->'c) =
let func ():'c = transformation this.Value
SomeOtherClass<'c> func
我没有看到任何阻止 transformation
返回与传递的类型不同的类型。我也不明白为什么第二个警告甚至是一个警告,因为显然我已经打算将新实例的 'b
类型参数设置为 'a*'a
.
我做错了什么?
泛型类型 SomeClass
在其构造函数中使用了泛型参数 'b
,但其定义中缺少该参数。将类型定义更改为
type SomeClass<'a, 'b when 'a:equality> ...
以及带有警告的行
SomeClass(func, this)
去除错误,返回的class类型为SomeClass<'c, ('a * 'a)>
.
虽然我不知道这是要达到什么目的,所以我无法判断这是否是一个明智的修正。