if, guards and pattern guards
if is an expression
In Haskell if is not a statement: it is an expression with a value, and both branches must be there. The type of the whole expression is the type of the two branches, so they have to agree.
sign :: Int -> String
sign n = if n < 0 then "negative" else if n == 0 then "zero" else "positive"
That is one expression, and it reads as a chain: the else of the first
condition is another if. It works, and it is the shape
that grows badly: three branches are already hard to scan, and each new case
adds a nesting level.
There is no else if keyword and no
return in a branch. A branch is an expression, and its
value is the value of the whole if:
main :: IO ()
main = print (if (2 :: Int) < 3 then "yes" else "no")
"yes"
The quotes are there because print shows a string as a string. A missing else is a syntax error, not a default of (): an expression must have a value on every path.
Guarded equations
A guard is a condition written between the arguments and the =. Several equations for one name are tried from the top, and the first whose guards all hold is used:
grade :: Int -> String
grade score
| score >= 90 = "A"
| score >= 80 = "B"
| score >= 70 = "C"
| otherwise = "F"
This is a single equation with four guarded right-hand sides, not four
equations; the vertical bar is the guard. The order matters: a score of 95
satisfies the first guard and the rest are never tested, which is why the
second guard can say >= 80 without also saying
< 90.
otherwise is not a keyword. It is an ordinary value
of type Bool, defined as True,
and it is used as the last guard because it always holds. A function whose
guards can all fail falls through to the next equation, and if there is none,
the program dies with a pattern-match failure at run time; the compiler warns
about that only for pattern matches, not for guards, so
otherwise is the habit that keeps a total function
total.
A pattern in a guard
A guard can also match a pattern, which is how a Maybe is taken apart and tested in one step:
describe :: Maybe Int -> String
describe value
| Just n <- value, n > 100 = "big " ++ show n
| Just n <- value = "small " ++ show n
| Nothing <- value = "nothing"
Just n <- value succeeds only when
value is a Just, and it binds
n to the number inside. The comma after it is a second
guard, so the first line means "if value is a Just and its number is over
100". The third line is a pattern that matches
Nothing; otherwise would do
the same and say less.
The name n is visible only in the right-hand side of
its own guard, which is why each line binds it again. This is the same
Maybe that the
lesson on Maybe uses for a
value that may be missing.
What hlint says about if
The program below starts with the nested if for sign, and hlint has an opinion about it:
Guards.hs:11:1-76: Suggestion: Use guards
Found:
sign n
= if n < 0 then
"negative"
else
if n == 0 then "zero" else "positive"
Perhaps:
sign n
| n < 0 = "negative"
| n == 0 = "zero"
| otherwise = "positive"
1 hint
The suggestion is the rewrite this lesson just described, and the two forms
are equivalent: the guards are tried in order and the first match wins, which
is what the chain of ifs does. The guarded version has
one condition per line, so a reader can compare them without following
parentheses.
hlint exits with 1 when it has a hint, which is why a
build script treats it as a check. Applying the suggestion by hand takes about
a minute and leaves a file that reports
No hints.
The final program
All three shapes in one file: guards for a table of ranges, guards for a three-way sign, and pattern guards over Maybe.
module Main (main) where
grade :: Int -> String
grade score
| score >= 90 = "A"
| score >= 80 = "B"
| score >= 70 = "C"
| otherwise = "F"
sign :: Int -> String
sign n
| n < 0 = "negative"
| n == 0 = "zero"
| otherwise = "positive"
describe :: Maybe Int -> String
describe value
| Just n <- value, n > 100 = "big " ++ show n
| Just n <- value = "small " ++ show n
| Nothing <- value = "nothing"
main :: IO ()
main = do
mapM_ (putStrLn . grade) [95, 85, 75, 10]
mapM_ (putStrLn . sign) [-3, 0, 3]
mapM_ (putStrLn . describe) [Just 200, Just 5, Nothing]
ghc -Wall -O1 -o Guards Guards.hs
./Guards
[1 of 2] Compiling Main ( Guards.hs, Guards.o )
[2 of 2] Linking Guards
A
B
C
F
negative
zero
positive
big 200
small 5
nothing
The build is clean under -Wall and hlint now says No hints. Note the fourth line: mapM_ (putStrLn . grade) prints one letter per score, and mapM_ is the map that runs an action for each element instead of building a list. The lesson on higher-order functions takes the composition apart.
Exercises
- Write abs' :: Int -> Int three times, with if, with guards, and with max n (-n). Which version is clearest, and which one would you have to change to work on Double?
- Give grade no otherwise line and call it with 60. What happens, and why did the compiler not warn about it?
- Add a guard to describe that returns "zero" for Just 0. Where does the line go, and what happens if you put it last?
- Run hlint Guards.hs before and after applying its suggestion. What is the exit status in each case?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What must be true of the two branches of an if expression?
Answer
They must have the same type
if is an expression with one type, so the then and else branches must both produce a value of that type.
-
What is otherwise?
Answer
An ordinary Bool value defined as True
otherwise is a normal value of type Bool equal to True, used as the last guard so the equation always succeeds.
-
In
| Just n <- value, n > 100, what is the part before the comma?Answer
A pattern guard that succeeds when value is a Just and binds n
A pattern guard matches the pattern and binds its variables; the comma starts the next guard.
-
Why does the order of guards matter in grade?
Answer
Because the first guard that holds decides the result
Guards are tried from the top, and the first one that holds is used, so score >= 80 is only reached when score < 90.
-
What does hlint suggest for a nested if on a value?
Answer
Guarded equations, with otherwise last
The Use guards hint rewrites the chain of ifs into one guarded equation per condition, ending with otherwise.
-
What does this program print?
module Main (main) where sign :: Int -> Int sign n = if n < 0 then -1 else 1 main :: IO () main = print (sign (-5))Answer
-1
The condition is true for a negative number, so the then branch is used and the value is -1.
-
What does this program print?
module Main (main) where grade :: Int -> String grade score | score >= 90 = "A" | score >= 80 = "B" | otherwise = "F" main :: IO () main = putStrLn (grade 85)Answer
B
85 fails the first guard and holds the second, so the result is B.
-
What does this program print?
module Main (main) where describe :: Maybe Int -> String describe value | Just n <- value, n > 100 = "big" | Just n <- value = "small " ++ show n | Nothing <- value = "nothing" main :: IO () main = putStrLn (describe (Just 5))Answer
small 5
The first guard fails on the number, the second matches the Just and prints the value.
-
A function has guards but no otherwise, and every guard fails for the argument. What happens?
Answer
The program fails at run time with a pattern-match error
With no equation left to try, evaluation fails at run time; -Wall does not warn about guards the way it warns about pattern matches.
-
What is the first line of the compiler output for this program?
module Main (main) where main :: IO () main = if 1 < 2 then putStrLn "yes"Answer
error: [GHC-58481]
if is an expression and needs both branches, so the parser reaches the end of the file expecting an else and reports a parse error, GHC-58481.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev