F#:有人可以解释我的编译器错误吗? [英] F#: Can someone explain my compiler error?
问题描述
任何人都知道这段代码是什么问题吗?
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
对于某些'd
和b : '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屋!