f# - 试图理解推断的类型约束

标签 f# type-inference type-constraints

以下产量

This construct causes code to be less generic than indicated by the type annotations. The type variable 'P has been constrained to be type 'bool'.



对于 let myValue = 的右侧表达,和

This code is less generic than required by its annotations because the explicit type variable 'P' could not be generalized. It was constrained to be 'bool'.



对于通用 <'P>Value方法:
type MyTypeA<'T> (myObject : 'T) as this =
    let myValue = this.Value<bool> "SomeBooleanProperty"

    member this.Value<'P> name = typeof<'T>.GetProperty(name, typeof<'P>).GetValue(myObject, null) :?> 'P`

但是,这编译得很好并且不会产生警告或错误:
type MyTypeB<'T> (myObject : 'T) as this =
    member this.Value<'P> name = typeof<'T>.GetProperty(name, typeof<'P>).GetValue(myObject, null) :?> 'P

    member this.Method<'P> name = this.Value<'P> name

这里发生了什么?为什么在第一个示例中,该方法在私有(private)值的分配中得到认可,而不是合法的通用方法?

最佳答案

警告 (FS0064)由 ConstraintSolver.fs 调用 SolveTyparEqualsTyp fun 中的 CheckWarnIfRigid 函数引发。
发出警告后,SolveTyparEqualsTyp 将继续(因为到目前为止没有错误)解决类型约束。
SolveTyparEqualsTyp 的评论是:

/// Add the constraint "ty1 = ty" to the constraint problem, where ty1 is a type variable. 
/// Propagate all effects of adding this constraint, e.g. to solve other variables 

这会导致成员 Value 出现错误 FS0663 OP示例中的定义。随后出现错误 FS0660。
出于某种我忽略的原因,发生了一些传播。

也许类型推断过于激进。
@jpe 和 OP 问题下方的其他评论包含更多有趣的线索。

关于f# - 试图理解推断的类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408743/

相关文章:

f# - 为什么我们不能通过类型扩展来满足 F# 静态成员约束?

haskell - "return 1"如何在 GHCi 中显示 "1"?

kotlin - Kotlin-字 rune 字与预期的Int类型不一致

go - 有没有办法检查值是否满足接口(interface)中定义的类型约束?

f# - 神奇的 sprintf 函数 - 如何包装它?

visual-studio-2012 - 未定义命名空间 "TypeProviders"(打开 Microsoft.FSharp.Data.TypeProviders)

c# - 如何确定该程序集是从 f# 项目编译而来的?

haskell - 为什么读取不能推导出正确的类型?

swift - 特定于枚举成员的通用约束

c# - 如何在另一个泛型基类上添加 C# 泛型类型约束?