gpt4 book ai didi

f# - 移动递归类型时代码中断

转载 作者:行者123 更新时间:2023-11-30 23:55:22 26 4
gpt4 key购买 nike

在重构一些代码的过程中,我注意到一种情况,即代码在移动时会中断:

type ThingBase () = class end

and Functions =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () = new 'T ()

and Thing () =
inherit ThingBase ()
static member Create () = Functions.Create<Thing> ()

// This works, but try moving the Functions type here instead.

如果将 Functions 类型移动到 Thing 类型下方,代码将意外中断:

type ThingBase () = class end

and Thing () =
inherit ThingBase ()
static member Create () = Functions.Create<Thing> ()
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// This construct causes code to be less generic than indicated by the
// type annotations. The type variable 'T has been constrained to be
// type 'Thing'.

and Functions =
static member Create<'T when 'T :> ThingBase and 'T : (new : Unit -> 'T)> () = new 'T ()
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// The type ''T' does not match the type 'Thing'.

而且无论我尝试什么,我都无法对其进行类型检查。为什么类型推断如此顽固,拒绝泛化 Create 方法。

顺便说一句,我还尝试了 F# 4.1 module rec 并且 Create 是否是模块中的函数也没有关系。

有什么见解吗?在我看来,编译器应该不会遇到任何问题。

最佳答案

如果你这样做,它会编译

static member Create<'T when 'T :> ThingBase 
and 'T : (new : Unit -> 'T)> () : 'T = new 'T ()
// ^^^^

明确说明返回类型的地方。

递归定义分两次从左到右进行类型检查;首先是函数/方法签名,然后是主体。您需要正文(或显式返回类型注释)来获取结果类型,因此您要么首先需要正文,要么需要注释,以便它在两遍中的第一遍中得到解决。

关于f# - 移动递归类型时代码中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230785/

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