共用方式為


條件表示式: 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!

另請參閱