F#:有人可以解释我的编译器错误吗? [英] F#: Can someone explain my compiler error?

查看:83
本文介绍了F#:有人可以解释我的编译器错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道这段代码是什么问题吗?

Anyone know what the problem with this code is?

let rec Foo(a,b) =
    match a () with
    | None -> Some(b)
    | Some(c) -> Some(Foo(c,b))

这是编译器错误:

类型不匹配.期望为'a,但给出了'a选项.当统一'a'和'a选项'时,结果类型将是无限的"

"Type mismatch. Expecting a 'a but given a 'a option The resulting type would be infinite when unifying ''a' and ''a option'"

推荐答案

让我们尝试在此处重现编译器如何推断类型的方法.

Let's try to reproduce how the compiler tries to infer types here.

let rec Foo(a,b) =
    match a () with
    | None -> Some(b)
    | Some(c) -> Some(Foo(c,b))

好,所以我看到了a ().a必须是从unit到某种类型的函数,我还不知道是哪个函数.我将其称为'a."

"Ok, so I see a (). a must be a function from unit to some type, I don't know which one yet. I'll call it 'a."

a : unit -> 'a

"a ()的结果与None/Some模式匹配.因此'a必须是'b option,并且c具有类型'b." (再次,'b代表未知,请输入.)

"The result of a () is matched with None/Some patterns. So 'a must be a 'b option and c has the type 'b." (Again, 'b stands for an unknown, as of yet, type).

a : unit -> 'b option
с : 'b

b上没有调用任何函数或方法(Some不会缩小类型,而Foo到目前为止我们还不知道类型).我将用'c表示其类型."

"No functions or methods are called on b (except Some, which doesn't narrow the type down, and Foo, the type of which we don't know so far). I'll denote its type by 'c."

a : unit -> 'b option
b : 'c
c : 'b

"Foo在其中一个分支中返回Some(b),因此返回类型必须为'c option."

"Foo returns Some(b) in one of the branches, so the return type must be 'c option."

Foo : (unit -> 'b option) * 'c -> 'c option

我做完了吗?否,我需要检查表达式中的所有类型是否有意义.让我们看一下,在Some(c)情况下,返回了Some(Foo(c,b)).所以Foo(c,b) : 'c.由于Foo返回一个option,我知道'c对于某些'db : 'd必须是'd option.等等,我已经有b : 'c,也就是b : 'd option.'d'd option有成为同一类型,但这是不可能的!定义中肯定有错误.我需要报告它."就是这样.

"Am I done yet? No, I need to check that all types in the expression make sense. Let's see, in the Some(c) case, Some(Foo(c,b)) is returned. So Foo(c,b) : 'c. Since Foo returns an option, I know 'c must be 'd option for some 'd, and b : 'd. Wait, I already have b : 'c, that is, b : 'd option. 'd and 'd option have to be the same type, but this is impossible! There must be an error in the definition. I need to report it." So it does.

这篇关于F#:有人可以解释我的编译器错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆