Skip to content
AgileLogics
5 min read

if/then/else Expressions

Prerequisites: Booleans and comparisons

In F#, if is an expression — it produces a value:

let temperature = 31

let advice =
    if temperature > 30 then "Stay in the shade"
    elif temperature > 15 then "Enjoy the weather"
    else "Take a jacket"

printfn "%s" advice
Stay in the shade
  • elif is short for "else if".
  • Every branch must return the same type — here, string.
  • Because if returns a value, you don't need a mutable variable or a ternary operator (?:) — if is the ternary operator.

Multi-line branches

Indent the branch body. The last expression in a branch is its value:

let describe n =
    if n < 0 then
        printfn "negative input!"
        "negative"
    else
        let kind = if n % 2 = 0 then "even" else "odd"
        $"a positive {kind} number"

printfn "%s" (describe 7)
printfn "%s" (describe -2)
a positive odd number
negative input!
negative

if without else

An if with no else must return unit — it's only for side effects:

let stock = 3
if stock < 5 then printfn "Low stock: reorder!"
Low stock: reorder!

Common mistakes

Branches with different types don't compile:

let x = 5
let result = if x > 0 then "positive" else 0
main.fsx(2,44): error FS0001: All branches of an 'if' expression must return values implicitly convertible to the type of the first branch, which here is 'string'. This branch returns a value of type 'int'.

Practice

Write a value grade that is "A" for scores of 90 or more, "B" for 80 or more, "C" for 70 or more, and "F" otherwise. Test it with a score of 84.

Show solution
let score = 84
let grade =
    if score >= 90 then "A"
    elif score >= 80 then "B"
    elif score >= 70 then "C"
    else "F"
printfn "Score %d: %s" score grade
Score 84: B