gpt4 book ai didi

f# - 函数自动向上转换的规则是什么?

转载 作者:行者123 更新时间:2023-12-03 10:05:01 24 4
gpt4 key购买 nike

在我的代码中,我有一个场景,我希望 F# 自动将一种函数类型(例如 IBase -> unit)的值向上转换为另一种明确指定的函数类型(IDerived -> unit)。虽然这似乎得到普遍支持,但我发现它没有明显原因而失败的情况。

在下面的代码中,case1case8似乎等同于我:在每种情况下,都有一个 IBase -> unit 类型的表达式在绑定(bind)到 IDerived -> unit 类型名称的右侧.那么为什么不允许第 4、5 和 7 种情况呢?

type IBase = interface end
type IDerived = inherit IBase

let foo (x: IBase) = ()
let bar = fun (x: IBase) -> ()

type T = T with static member (!!) (_: T) = foo
let baz = !!T

let case1: IDerived -> unit = foo // OK
let case2: IDerived -> unit = bar // OK
let case3: IDerived -> unit = baz // OK
let case4: IDerived -> unit = !!T // Expecting 'IDerived -> unit' but given 'IBase -> unit'
let case5: IDerived -> unit = upcast !!T // Type 'IBase -> unit' is not compatible with type 'IDerived -> unit'
let case6: IDerived -> unit = let z = !!T in z // OK
let case7: IDerived -> unit = fun (x: IBase) -> () // Expected x to have type 'IDerived' but here has type 'IBase'
let case8: IDerived -> unit = let z = fun (x: IBase) -> () in z // OK

编辑:为了澄清,我最想知道为什么编译器没有平等对待这 8 种情况。例如,我希望绑定(bind) let z...case8是多余的,但它有所作为(与 case7 相比)。为什么?

编辑:这里有一些代码来演示我想要实现的目标: https://dotnetfiddle.net/AlpdpO它还包含一个解决方案/解决方法,所以我真的要求更多的技术细节/原因,而不是替代方法。我已经考虑在 GitHub 上提出一个问题,但感觉这个问题很可能只是我这边的一个误解。

最佳答案

F# 的类型推断似乎不够聪明,无法处理其中的一些情况,但您可以通过更明确的定义来帮助解决这个问题。试试这个:

type IBase = interface end
type IDerived = inherit IBase

let foo (x: IBase) = ()

type T = T with static member (!!) (_: T) : #IBase -> unit = foo

let case4: IDerived -> unit = !!T
let case5: IDerived -> unit = upcast !!T
let case7: IDerived -> unit = fun (x: #IBase) -> ()

...当然,您最初的通过案例也将继续通过。问题是 F# 对 (!!) 函数的类型和 lambda 的类型有点过于严格,所以我们可以通过显式类型注释来帮助它,上面写着“ IBase 或其任何一个衍生品在这里很好”。

无论如何,为这些语法案例提交错误。正如 F# 编译器在这里所​​做的那样,编译器在类型方面犯错并不是一件非常糟糕的事情。如果过于宽松,可能会发生更糟糕的事情。在这里,最坏的影响是你必须为它做一些打字工作。

我应该指出,这实际上与强制转换无关,并且不会发生强制转换( upcast 被忽略)。真正的问题是解释的严格性。试试这个代码,你会看到表明这一点的警告。

关于f# - 函数自动向上转换的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54372555/

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