条件式:if...then...else
Conditional Expressions: if...then...else
式if...then...else
は、コードの異なる分岐を実行し、指定されたブール式に応じて別の値に評価されます。The if...then...else
expression runs different branches of code and also evaluates to a different value depending on the Boolean expression given.
構文Syntax
if boolean-expression then expression1 [ else expression2 ]
RemarksRemarks
前の構文では 、ブール式がにtrue
評価されると、expression1 が実行されます。それ以外の場合は、 expression2が実行されます。In the previous syntax, expression1 runs when the Boolean expression evaluates to true
; otherwise, expression2 runs.
他の言語if...then...else
とは異なり、コンストラクトはステートメントではなく、式です。Unlike in other languages, the if...then...else
construct is an expression, not a statement. つまり、値が生成されます。これは、が実行される分岐の最後の式の値です。That means that it produces a value, which is the value of the last expression in the branch that executes. 各分岐で生成される値の型が一致している必要があります。The types of the values produced in each branch must match. 明示的else
な分岐がない場合、その型unit
はになります。If there is no explicit else
branch, its type is unit
. したがって、 then
分岐の型が以外unit
の型である場合は、同じ戻り値else
の型を持つ分岐が存在する必要があります。Therefore, if the type of the then
branch is any type other than unit
, there must be an else
branch with the same return type. 式を連結する場合は、のelse if
代わりにelif
キーワードを使用できます。これらは等価です。 if...then...else
When chaining if...then...else
expressions together, you can use the keyword elif
instead of else if
; they are equivalent.
例Example
次の例は、式のif...then...else
使用方法を示しています。The following example illustrates how to use the if...then...else
expression.
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!
関連項目See also
フィードバック
フィードバックを読み込んでいます...