If Else in F#

Branching with if and else in F# is straightforward.

open System

// Here's a basic example.
if 7 % 2 = 0 then
    printfn "7 is even"
else
    printfn "7 is odd"

// You can have an `if` statement without an else.
if 8 % 4 = 0 then
    printfn "8 is divisible by 4"

// Logical operators like `&&` and `||` are often useful in conditions.
if 8 % 2 = 0 || 7 % 2 = 0 then
    printfn "either 8 or 7 are even"

// In F#, you can use `let` bindings before conditionals.
// Any values declared here are available in the current and all subsequent branches.
let num = 9
if num < 0 then
    printfn "%d is negative" num
elif num < 10 then
    printfn "%d has 1 digit" num
else
    printfn "%d has multiple digits" num

To run this F# program, you can save it as a .fs file and use the F# compiler (fsc) or the F# Interactive (dotnet fsi).

$ dotnet fsi if-else.fs
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in F#, you don’t need parentheses around conditions, and the then keyword is used instead of curly braces. The elif keyword is used for “else if” conditions.

F# also supports pattern matching, which can often be used as a more powerful alternative to if-else statements for complex branching logic.