F#推断If/Then中的类型

编程入门 行业动态 更新时间:2024-10-23 07:20:16
本文介绍了F#推断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中的类型

本文发布于:2023-07-30 15:17:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250562.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:推断   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!