F#类型推理比类型注释所指示的更不通用



在以下代码片段的最后一行中,我得到了两个警告: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)

删除错误,并且返回的类的类型为SomeClass<'c, ('a * 'a)>

不过,我不知道这是为了实现什么,所以我无法判断这是否是一个明智的纠正

最新更新