🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Guards

A guard is a line that lets a function choose a result when a condition holds. The function tests its guard lines in order.

The top guard wins first

The score 92 passes the first guard. That guard gives the result A.

grade score
  | score >= 90 = "A"
  | score >= 50 = "Pass"
  | otherwise = "Fail"
main :: IO ()
main = putStrLn (grade 92)

otherwise catches the rest

The price 40 passes neither number guard. The otherwise line gives the result 0.

discount price
  | price >= 100 = 20
  | price >= 50 = 10
  | otherwise = 0
main :: IO ()
main = print (discount 40)

A guard can change a negative input

The input -7 fails the first guard. The otherwise line subtracts it from 0.

absolute n
  | n >= 0 = n
  | otherwise = 0 - n
main :: IO ()
main = print (absolute (-7))

Example

ticketPrice age
  | age < 12 = 5
  | age >= 65 = 7
  | otherwise = 12
main :: IO ()
main = print (ticketPrice 70)

Key points

  • Guard: a guard is a condition written after a vertical bar in a definition.
  • Result: each guard line writes its result after the equals sign.
  • Order: Haskell tests the guard lines from top to bottom.
  • First true guard: the first guard that is True supplies the result.
  • otherwise: the otherwise guard is True and catches every remaining value.

In this example, ticketPrice tests its guards in order for the age 70, the first guard is False, the second guard is True, and print writes that guard's result 7.

Note

guards belong to a function definition and never appear in main.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

A function has guards for scores of at least 90 and at least 50, then an otherwise guard that gives Fail. What does it give for a score of 40?