elif
In programs we usually use ifs to execute statements inside the blocks. But in F# we can use an if
-construct to return a value. It is part of an expression.
By turning an if
-statement into an expression, we can use "if" in more ways. We can assign to the result of an if.
This program uses an if, elif
, else construct. It first creates a string
. Then it tests the length of this string
in the if
-statement.
if
-condition. A "then" is also required for an elif
, but not an else.if
-statement must be in parentheses.let animal = "bird" // Test the length of the string. if (animal.Length = 1) then // Not reached. printfn "A" elif (animal.Length = 2) then // Not reached. printfn "B" else // This statement is reached. printfn "C"C
An if
-statement can be used to return a value (as an expression). We can embed an if in more complex statements. Here we assign the value of "result" with an if.
let count = 50 // Use an if, elif, else construct within a variable assignment. let result = if count >= 200 then 1 elif count <= 100 then 2 else 3 // Write results. printfn "%A" count printfn "%A" result50 2
There is no "!=" operator for ints in F#. To see if an int
does not equal a value, we use the equals operator and then surround that expression with the "not" operator.
let code = 10 // Use an if-not statement to test a variable. if not (code = 5) then printfn "Not five!"Not five!
Match
versus ifWe can write a logical test with a match or an if
-expression. The syntax for match is closer to a "switch
" in C-like languages. A match may be easier to use an expression.
if
-statement. You can see this version looks more like C# or C code.// We can use a match to handle the argument. let testPrint v = match v with | 0 | 1 | 2 -> printfn "[MATCH] branch A: %A" v | _ -> printfn "[MATCH] branch B: %A" v // We can use an if-else to handle the argument. let testPrintIf v = if v = 0 || v = 1 || v = 2 then printfn "[IF] branch A: %A" v else printfn "[IF] branch B: %A" v // Test functions. testPrint 0 testPrint 9 testPrintIf 0 testPrintIf 9[MATCH] branch A: 0 [MATCH] branch B: 9 [IF] branch A: 0 [IF] branch B: 9
bool
to int
F# offers no C-like ternary operator. Instead, we use inline if
-expressions. With an if
-expression we can convert a bool
to an int
.
An if
-block operates in F# much like in other languages. But it has a special feature. It can evaluate an if as an expression, which can return values or be used in assignments.