Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 57 ยท Functions

Guards, where and let

Write conditions with Haskell guards and if-then-else, then name intermediate values with where and let. Includes otherwise and MultiWayIf.

Pattern matching answers "what shape is this value?". Often you also need to ask "is this number big enough?" or "does this string satisfy some rule?". Haskell has two tools for conditions, guards and if-then-else, and two tools for naming intermediate values, where and let.

This lesson shows each of them, explains when to choose which, and mentions one extension, MultiWayIf, that is popular in modern code.

GHC is not installed on this site, so Haskell code blocks are read-only. The editors use JavaScript stand-ins that mirror the structure of the Haskell definitions.

Guards

A guard is a Boolean condition written after a vertical bar | and before the =. The function body is the expression of the first guard that is True.

HASKELL
grade :: Int -> Char
grade score
  | score >= 90 = 'A'
  | score >= 80 = 'B'
  | score >= 70 = 'C'
  | otherwise   = 'F'

Read it like a table: for the argument score, try each row from the top. otherwise is not a keyword. It is a plain value defined as True, which makes it a readable catch-all for the last row.

Guards are tried top to bottom, so the order matters. Here a score of 95 satisfies all three of the first conditions, but only the first one counts.

Guards can combine with pattern matching in one definition. If every guard of an equation fails, Haskell falls through to the next equation, which is a feature that surprises newcomers:

HASKELL
describe :: [Int] -> String
describe xs
  | null xs   = "empty"
describe (x : _)
  | x > 100   = "starts big"
  | x < 0     = "starts negative"
describe _    = "something else"

For [5, 6] the first equation's guard fails, the second equation matches the pattern but both guards fail, and the third catches it.

Pattern guards

A guard can also be a pattern match with <-. If it matches, the variables it binds are available in the body:

HASKELL
import qualified Data.Map as Map

price :: Map.Map String Int -> String -> String
price table item
  | Just p <- Map.lookup item table = item ++ " costs " ++ show p
  | otherwise                       = item ++ " is not for sale"

This is a tidy way to unwrap a Maybe without a nested case. You will see Map in Essential Libraries.

if-then-else

if is an expression that picks between two values. Both branches are required, and both must have the same type.

HASKELL
absolute :: Int -> Int
absolute n = if n < 0 then negate n else n

label :: Int -> String
label n = "You have " ++ show n ++ (if n == 1 then " item" else " items")

Because if is an expression, there is no "if without else": every possible input must produce a value. Compare this with statements in other languages, where if just runs code. When you have more than two outcomes, a guard list reads better than nested ifs.

where: names for a whole equation

where introduces local definitions that are visible in all guards and the body of one equation. It comes after the equation.

HASKELL
bmiCategory :: Double -> Double -> String
bmiCategory weightKg heightM
  | bmi < 18.5 = "underweight"
  | bmi < 25.0 = "normal"
  | otherwise  = "overweight"
  where
    bmi = weightKg / heightM ^ 2

Without where, you would repeat weightKg / heightM ^ 2 in every guard. where bindings can define helper functions as well, and later bindings can use earlier ones:

HASKELL
hypotenuse :: Double -> Double -> Double
hypotenuse a b = sqrt squares
  where
    squares = square a + square b
    square x = x * x

The scope of a where is that one equation only. If you have two equations (say, two patterns), each needs its own where.

let ... in: names for one expression

let also defines local names, but it is an expression and the names are visible only after in.

HASKELL
let a = 3
    b = 4
in sqrt (a * a + b * b)
-- 5.0

Because let ... in ... is an expression, you can place it anywhere an expression is allowed, for example inside another calculation:

HASKELL
cylinderVolume :: Double -> Double -> Double
cylinderVolume r h =
  let base = pi * r ^ 2
  in base * h

total :: Double
total = 10 + (let x = 5 in x * x)   -- 35.0

In GHCi and inside do blocks, let is written without in. That form is a statement, not an expression, and you will meet it in IO Basics.

where or let?

where After the equation. Covers all its guards.
let ... in An expression. Usable anywhere inline.

Both are lazy. A name that is never used is never computed.

1 / 2

Which one should I use?

  • where is the usual choice when the helpers are used by several guards or when you want to show the main idea first and the details after it.
  • let is handy for a quick local name inside a longer expression, or in a spot where where cannot reach, like inside a lambda.
  • Both are lazy. A binding that is never needed is never evaluated, so defining an expensive value and using it only on some branches costs nothing on the other branches. Lazy Evaluation goes deeper.
  • Indentation counts. Bindings in the same block must start in the same column. See the layout rule in Your First Haskell Program.

MultiWayIf

GHC offers an extension that writes guard-style conditions inside an expression. Enable it with a pragma at the top of the file:

HASKELL
# LANGUAGE MultiWayIf #

sign :: Int -> String
sign n = if | n < 0     -> "negative"
            | n == 0    -> "zero"
            | otherwise -> "positive"

It is not part of standard Haskell 2010, so use it only when a plain guard or case would be clumsier. More on extensions in GHC Extensions Worth Knowing.

Practising with a stand-in

The editor below uses JavaScript to mirror these definitions. The grade function plays the guard list, the bmiCategory function uses a local constant like where, and the immediately-invoked arrow function imitates let ... in. This is only a stand-in: in Haskell the local bindings are lazy, whereas in JavaScript the const runs immediately.

JS Guards, where and let in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try changing the thresholds in grade, then add a case that makes two conditions overlap to see how the first match wins.

Falling through to the next equation is an idea that JavaScript does not have natively. The second editor models a function as a list of equations, each with a guard that may decline, and tries them in order.

JS Equations that fall through

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The final throw is what Haskell does when no equation fits. Here the last equation always matches, so it never fires.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is otherwise in a guard?

    otherwise is defined in the Prelude as True, so the last guard always succeeds.
  2. 2. What happens if every guard of an equation is False?

    Guard failure falls through to the next equation. If there is none, you get a non-exhaustive patterns error at run time.
  3. 3. Which statement about if-then-else in Haskell is true?

    if is an expression, so it must always produce a value of one type.
  4. 4. Where are where bindings visible?

    where scopes over the equation it is attached to, including all its guards. let ... in only scopes over the expression after in.
  5. 5. What do you need to write if | x < 0 -> ... | otherwise -> ...?

    Multi-way if is a GHC extension enabled by {-# LANGUAGE MultiWayIf #-}.

Summary

  • Guards (| condition = result) pick a result by trying conditions top to bottom; otherwise is just True.
  • If every guard fails, evaluation falls through to the next equation.
  • if cond then a else b is an expression, so else is required.
  • where names values for a whole equation, guards included; let ... in names values for a single expression.
  • MultiWayIf is an optional GHC extension for guard-style conditions inside expressions.

Next, make functions call themselves: Recursion.