條件運算式:if...then...else

if...then...else 運算式會根據指定的布林運算式,執行不同的程式碼分支,也會評估出不同的值。

語法

if boolean-expression then expression1 [ else expression2 ]

備註

在先前的語法中,當布林運算式評估為 true 時,會執行 expression1,否則會執行 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!

另請參閱