gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:42:16 25 4
gpt4 key购买 nike

以下产量

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com