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

if...then...else 表达式不仅可运行代码的不同分支,还可计算为不同的值,具体取决于给定的布尔表达式。

语法

if boolean-expression then expression1 [ else expression2 ]

备注

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

与其他语言一样,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!

另请参阅