条件表达式:if... then...else (F#)

根据给定的布尔表达式,if...then...else 表达式不仅可以运行代码的不同分支,还可以计算为不同的值。

if Boolean-expression then expression1 [ else expression2 ]

备注

在前面的语法中,如果布尔表达式的计算结果为 true,则运行 expression1;否则运行 expression2。

与其他语言不同,if...then...else 构造是一个表达式,而非一个语句。 这意味着,它生成的值是所执行分支中的最后一个表达式的值。 每个分支中生成的值的类型必须匹配。 如果没有显式的 else 分支,则此表达式的类型为 unit。 因此,如果 then 分支的类型是除 unit 之外的任何类型,则必须存在具有相同返回类型的 else 分支。 将 if...then...else 表达式链接在一起时,可以使用关键字 elif 来代替使用 else if;它们是等效的。

示例

下面的示例演示如何使用 if...then...else 表达式。

let test x y =
  if x = y then "equals"
  elif x < y then "is less than"
  else "is greater than"

printfn "%d %s %d." 10 (test 10 20) 20

printfn "What is your name? "
let nameString = System.Console.ReadLine()

printfn "What is your age? "
let ageString = System.Console.ReadLine()
let age = System.Int32.Parse(ageString)

if age < 10
then printfn "You are only %d years old and already learning F#? Wow!" age
      

请参见

其他资源

F# 语言参考