F#推断If/Then中的类型 [英] F# inferred types in If/Then
问题描述
如果我具有以下功能:
let myFunc x y =
if y = 0 then 1
x
我得到了错误:
Program.fs(58,17): error FS0001: This expression was expected to have type
unit
but here has type
int
为什么编译器期望'unit'而不是int?
Why does the compiler expect 'unit' instead of int ?
推荐答案
可能值得补充的是,这不仅仅是if
的属性. F#是一种基于表达式的语言,这意味着几乎每段代码(除了类型声明和一些例外情况)都是一种 expression ,其计算结果是某些结果.实际上,F#不会调用if 语句的if
,而是if if的表达式 .
It might worth adding that this is not just a property of if
. F# is an expression-based language meaning that pretty much every piece of code (aside from type declarations and a few exceptions) is an expression that evaluates to some result. In fact, F# does not call if
the if statement, but an if expression.
这意味着您可以在意外的地方使用if
.例如,这可能很有用:
This means that you can use if
in unexpected places. For example, this might be useful:
x/2 + (if x%2=0 then 0 else 1)
正如Garry所解释的那样,如果您省略else
,则该表达式仍需要返回某些内容-如果结果为int
,则这将毫无意义(编译器应选择哪个数字) ?),因此它要求结果的类型为unit
,这是代表无结果"的特殊类型.
As already explained by Garry, if you omit else
, then the expression still needs to return something - if the result was to be an int
, then it would not really make sense (which number should the compiler pick?), so it requires that the result is of type unit
, which is a special type representing "no result".
unit
类型也是所有命令式函数(例如printf
)或逻辑上不返回任何值的所有表达式(赋值或例如循环)的结果.这意味着如果您写:
The unit
type is also the result of all imperative functions (e.g. printf
) or of all expressions that do not logically return any value (assignment or e.g. loop). This means that if you write:
if x > 0 then printfn "Big!"
...则表达式的类型正确,因为printfn "Big!"
的返回类型为unit
,并且隐式添加的else
分支也返回unit
.您可以直接手动创建类型为unit
的值(该类型只有一个值),因此上面的内容实际上对应于:
... then the expression is well-typed, because printfn "Big!"
has a return type unit
and the implicitly added else
branch also returns unit
. You can create a value of type unit
directly by hand (the type has exactly one value), so the above actually corresponds to:
if x > 0 then printfn "Big!" else ()
从C#角度来看,将if .. then .. else
用作条件运算符更有意义:
From the C# perspective, it makes more sense to read if .. then .. else
as the conditional operator:
x/2 + (x%2 == 0 ? 0 : 1)
这篇关于F#推断If/Then中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!