Haskell Guards, where & let
Pattern matching chooses an equation by the shape of the input. Guards choose by conditions. Together with where and let, which name intermediate values, they let you write decision logic that reads almost like a specification.
Guards
A guard is a | followed by a Boolean expression. The first guard that is True decides the result. otherwise is simply another name for True, used as the final catch-all:
grade :: Int -> Char
grade score
| score >= 90 = 'A'
| score >= 80 = 'B'
| score >= 70 = 'C'
| score >= 60 = 'D'
| otherwise = 'F'
main :: IO ()
main = do
print (map grade [95, 83, 70, 64, 12])"ABCDF"
Compare it with nested ifs: if score >= 90 then 'A' else if score >= 80 then 'B' else …. Guards are flatter and easier to extend.
Guards and patterns combine freely. Each equation can have its own guards, and if all guards of an equation fail, GHC moves on to the next equation:
classify :: [Int] -> String
classify [] = "no data"
classify xs
| all (> 0) xs = "all positive"
| any (== 0) xs = "contains zero"
classify _ = "mixed"
main :: IO ()
main = mapM_ (putStrLn . classify) [[], [3, 1], [4, 0, -2], [5, -5]]no data
all positive
contains zero
mixed
where: naming things after the fact
A where clause attaches local definitions to an equation. They are visible in all of its guards, which avoids repeating a calculation:
shippingCost :: Double -> Double -> String
shippingCost weightKg distanceKm
| cost < 5 = "Flat rate: 5.0"
| cost > maxCost = "Capped: " ++ show maxCost
| otherwise = "Cost: " ++ show cost
where
cost = baseFee + weightKg * perKg + distanceKm * perKm
baseFee = 2.0
perKg = 1.5
perKm = 0.02
maxCost = 40.0
main :: IO ()
main = do
putStrLn (shippingCost 1 50)
putStrLn (shippingCost 4 200)
putStrLn (shippingCost 20 900)Flat rate: 5.0
Cost: 12.0
Capped: 40.0
The order of the where definitions doesn't matter: cost uses baseFee even though it is defined below it. Definitions in Haskell are equations, not steps.
where bindings can also use pattern matching and define helper functions:
describeTriangle :: Double -> Double -> Double -> String
describeTriangle a b c
| not valid = "not a triangle"
| a == b && b == c = "equilateral, area " ++ rounded
| a == b || b == c || a == c = "isosceles, area " ++ rounded
| otherwise = "scalene, area " ++ rounded
where
valid = a + b > c && a + c > b && b + c > a
s = (a + b + c) / 2
area = sqrt (s * (s - a) * (s - b) * (s - c))
rounded = show (round2 area)
round2 x = fromIntegral (round (x * 100)) / 100
main :: IO ()
main = do
putStrLn (describeTriangle 3 4 5)
putStrLn (describeTriangle 2 2 2)
putStrLn (describeTriangle 5 5 8)
putStrLn (describeTriangle 1 2 10)scalene, area 6.0
equilateral, area 1.73
isosceles, area 12.0
not a triangle
Thanks to laziness, area is only computed when a guard actually uses rounded, so the invalid triangle never takes the square root of a negative number.
let … in: naming things up front
let bindings in expression is an expression: it defines names and then evaluates the part after in. Use it when the names are only needed in one place:
cylinderSurface :: Double -> Double -> Double
cylinderSurface r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea + 2 * topArea
main :: IO ()
main = do
print (cylinderSurface 1 2)
print (let x = 3; y = 4 in x * x + y * y)
print [let sq = n * n in sq + 1 | n <- [1 .. 4]]18.84955592153876
25
[2,5,10,17]
On one line, separate bindings with semicolons. Inside a do block you write let without in, as you've already seen; the names are then visible in the rest of the block.
where versus let
where |
let … in |
|
|---|---|---|
| Position | after the function body | before the expression that uses it |
| Kind | part of an equation (a declaration) | an expression, usable anywhere |
| Scope | the whole equation, including all guards | only the expression after in |
| Typical use | helper values and functions for a definition | a quick local name inside a bigger expression |
Both are equally efficient. Most Haskell code prefers where for function-level helpers because the main idea comes first and the details follow.
Tip: A frequent beginner error is indentation:
wheremust be indented more than the function name, and all the bindings in awhereorletblock must line up in the same column.
Test yourself
What is otherwise in a guard?
- A keyword that catches errors
- A name for
True - The same as
else, only valid inif - A wildcard pattern
Which bindings can all the guards of an equation use?
- Bindings in a
letinside the first guard - Bindings in the equation's
whereclause - None: guards can only use parameters
- Global variables only
What does let a = 2; b = 5 in a * b + 1 evaluate to?
- 11
- 12
- 7
- A syntax error