case expressions
case is an expression
case takes a value, tries a list of alternatives, and the whole construct is an expression with the type of its branches. There is no fall-through and no break: the first alternative whose pattern matches produces the value, and every alternative must have the same type.
describe :: Maybe Int -> String
describe value = case value of
Nothing -> "nothing"
Just n
| n < 0 -> "negative " ++ show n
| otherwise -> "positive " ++ show n
The layout matters: the alternatives are indented under of, and the guards of one alternative are indented under their pattern. A branch may be a guarded right-hand side, which is how case and guards combine: the pattern decides the shape, the guard decides the value.
Matching a Maybe
Maybe has two constructors, Nothing and Just a, so a case over it has two alternatives and the compiler can check that both are there. That is the point of the type: a missing Nothing case is a warning from -Wincomplete-patterns, not a crash that waits for the input.
module Main (main) where
describe :: Maybe Int -> String
describe value = case value of
Nothing -> "nothing"
Just n
| n < 0 -> "negative " ++ show n
| otherwise -> "positive " ++ show n
main :: IO ()
main = do
putStrLn (describe Nothing)
putStrLn (describe (Just 3))
putStrLn (describe (Just (-2)))
ghc -Wall -O1 -o casemaybe casemaybe.hs
./casemaybe
nothing
positive 3
negative -2
The build is clean and hlint is silent: both constructors are covered, and the guards inside Just end in otherwise, so the inner case analysis is complete too. Without that otherwise, a Just 0 would fall out of the branch and the program would fail at run time with a pattern-match error.
Nesting and guards
A branch of a case is an expression, so it can be another case. That is how a pair of values is classified without writing a function for every combination: match the pair, then match its components.
module Main (main) where
classify :: (Int, Int) -> String
classify pair = case pair of
(0, 0) -> "origin"
(x, 0) -> "x axis at " ++ show x
(0, y) -> "y axis at " ++ show y
(x, y) -> "point " ++ show x ++ ", " ++ show y
main :: IO ()
main = do
putStrLn (classify (0, 0))
putStrLn (classify (4, 0))
putStrLn (classify (0, 5))
putStrLn (classify (2, 3))
ghc -Wall -O1 -o point point.hs
./point
origin
x axis at 4
y axis at 5
point 2, 3
The order of the alternatives is again the semantics: (0, 0) must come before (x, 0), or the origin would be reported as a point on the x axis. The last alternative is the catch-all, and it is the one that makes the function total for every pair.
A branch can also be a let or a do block, and a case can sit on the right of <- in a do, which is how the lesson on IO reads a value and classifies it in one step.
case against equations
The same classification written as equations of a function is shorter when the case analysis is the whole body, and it is what the lesson on pattern matching showed. The two forms compile to the same case analysis:
classifyEq :: (Int, Int) -> String
classifyEq (0, 0) = "origin"
classifyEq (x, 0) = "x axis at " ++ show x
classifyEq (0, y) = "y axis at " ++ show y
classifyEq (x, y) = "point " ++ show x ++ ", " ++ show y
map classifyEq [(0, 0), (4, 0), (0, 5), (2, 3)]
== map classify [(0, 0), (4, 0), (0, 5), (2, 3)] -- True
The rule of thumb the course follows: use equations when the function is only a case analysis, and use case when the value to match is not an argument, when there is work before the match, or when the match is one step of a longer pipeline. A case inside a where block that mirrors the arguments is a sign that equations would be shorter.
Exercises
- Write safeDiv :: Int -> Int -> Maybe Int with a case on the divisor, and print three calls.
- Add a case over a Bool inside a where block and say whether equations would be shorter.
- Reorder the alternatives of classify so that (x, 0) comes first, and predict the output for (0, 0) before you run it.
- Remove the otherwise guard from the Just branch and compile: which warning appears, and what happens when the program runs?
- Write a case that matches a three-constructor type of your own and explain why the compiler can check it.
- Compare the equations and the case version of classify with hlint.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What kind of thing is
case ... ofin Haskell?Answer
An expression with the type of its branches
case is an expression: every alternative produces a value of the same type, and the whole construct can appear anywhere a value can.
-
How many alternatives does a case over
Maybe Intneed to be complete?Answer
Two: Nothing and Just n
Maybe has exactly two constructors, so two alternatives cover every value and the compiler can prove it.
-
What does this program print?
module Main (main) where describe :: Maybe Int -> String describe value = case value of Nothing -> "nothing" Just n | n < 0 -> "negative " ++ show n | otherwise -> "positive " ++ show n main :: IO () main = putStrLn (describe (Just 3))Answer
positive 3
Just 3 matches the second alternative, the first guard fails and otherwise holds, so the branch prints positive 3.
-
What happens if the Just branch has guards but no otherwise and none of them holds?
Answer
The program fails at run time with a pattern-match error
A case with no matching alternative fails when the value is forced; -Wincomplete-patterns warns when it can see the gap.
-
In
classify, why must(0, 0)come before(x, 0)?Answer
(x, 0)matches the origin too, so the origin branch would be unreachableAlternatives are tried in order, and a variable matches 0 as well, so the specific pattern has to come first.
-
What does this program print?
module Main (main) where classify :: (Int, Int) -> String classify pair = case pair of (0, 0) -> "origin" (x, 0) -> "x axis at " ++ show x (0, y) -> "y axis at " ++ show y (x, y) -> "point " ++ show x ++ ", " ++ show y main :: IO () main = putStrLn (classify (0, 5))Answer
y axis at 5
The pair (0, 5) fails the first two alternatives and matches (0, y) with y = 5.
-
When is a function written with equations shorter than the same function with case?
Answer
When the whole body is a case analysis of the arguments
Equations fold the match into the definition of the function; a case that only mirrors the arguments repeats the function name in every branch.
-
Can a case branch be a guarded right-hand side, as in
Just n | n < 0 -> ...?Answer
Yes, and the guards are tried in order inside that alternative
A case alternative takes the same right-hand side forms as an equation, guards included.
-
What does a case expression require of all its alternatives?
Answer
They produce the same type
The case is an expression with one type, so every branch must produce a value of that type.
-
What does this program print?
module Main (main) where main :: IO () main = print (case (1, 2) of (0, 0) -> 0 :: Int (x, y) -> x + y)Answer
3
The first alternative does not match, the catch-all binds x = 1 and y = 2, and the branch returns their sum.
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