条件表达式: if...then...else

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

语法

if boolean-expression then expression1 [ else expression2 ]

注解

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

与其他语言一样, if...then...else 该构造可用于有条件地执行代码。 在 F# 中,是一个表达式, if...then...else 由执行的分支生成值。 每个分支中的表达式类型必须匹配。

如果没有显式 else 分支,则总体类型为 unit,并且分支的类型 then 也必须是 unit

将表达式链接 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
10 is less than 20
What is your name? John
How old are you? 9
You are only 9 years old and already learning F#? Wow!

另请参阅