F# if then else
The if then else
expression in F# is used for conditional statements. It allows the program to execute one block of code if a condition is true, and another block of code if the condition is false. It follows the syntax format:
if [condition] then [true_branch] else [false_branch]
where [condition]
is the boolean expression to be tested, [true_branch]
is the code block to be executed if the condition is true, and [false_branch]
is the code block to be executed if the condition is false.
Syntax
if [condition] then
[true branch]
else
[false branch]
Example
let num = 10
if num < 5 then
printfn "The number is less than 5"
else
printfn "The number is greater than or equal to 5"
Output
The number is greater than or equal to 5
Explanation
In the above example, the num
variable is assigned a value of 10. The if then else
expression is used to evaluate whether num
is less than 5 or not. Since this condition is false, the code block in the false branch gets executed and prints out "The number is greater than or equal to 5" as the output.
Use
The if then else
expression is useful for making decisions and controlling the flow of program execution based on specific conditions. It is commonly used in programs that involve input validation, error handling, and other complex logic.
Important Points
- The condition in an
if then else
statement must be a boolean expression, which evaluates totrue
orfalse
. - Both the true branch and the false branch must have the same type of value.
- Nested
if then else
expressions can be used to create more complex logic.
Summary
The if then else
expression in F# is a powerful tool for writing programs that make decisions based on specific conditions. It allows the program to execute one block of code if a condition is true, and another block of code if the condition is false. It is one of the fundamental constructs used in many F# programs.