TExcelTAD
Home › Haskell › Haskell Case Expressions

Haskell Case Expressions

Function equations are one place to pattern match. A case expression lets you match on any value, anywhere in your code, not just on a function's parameters. In fact, multiple function equations are just a convenient way of writing a case.

haskell · try it yourself
weekdayName :: Int -> String
weekdayName n = case n of
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  _ -> "invalid day"

main :: IO ()
main = mapM_ (putStrLn . weekdayName) [1, 5, 7, 9]
Monday
Friday
Sunday
invalid day

The syntax is case expression of, followed by alternatives of the form pattern -> result, all indented to the same column. Like if, a case is an expression that produces a value, so every alternative must have the same type.

Matching on computed values

The real strength of case is matching on something you calculate inside a function, which equations can't do directly:

haskell · try it yourself
describeInput :: String -> String
describeInput input = case words input of
  [] -> "nothing typed"
  [single] -> "one word: " ++ single
  ("help" : _) -> "showing help"
  (cmd : args) -> "command " ++ cmd ++ " with " ++ show (length args) ++ " argument(s)"

main :: IO ()
main = do
  putStrLn (describeInput "   ")
  putStrLn (describeInput "status")
  putStrLn (describeInput "help me please")
  putStrLn (describeInput "copy a.txt b.txt")
nothing typed
one word: status
showing help
command copy with 2 argument(s)

Case on Maybe and tuples

A very common use is unpacking a Maybe result, deciding what to do when the value is missing:

haskell · try it yourself
prices :: [(String, Double)]
prices = [("coffee", 3.2), ("bagel", 2.5), ("juice", 4.0)]

receiptLine :: String -> String
receiptLine item = case lookup item prices of
  Just price -> item ++ ": " ++ show price
  Nothing -> item ++ ": not on the menu"

compareScores :: Int -> Int -> String
compareScores mine theirs = case (compare mine theirs, mine - theirs) of
  (GT, diff) -> "won by " ++ show diff
  (LT, diff) -> "lost by " ++ show (abs diff)
  (EQ, _) -> "draw"

main :: IO ()
main = do
  mapM_ (putStrLn . receiptLine) ["bagel", "tea"]
  putStrLn (compareScores 3 1)
  putStrLn (compareScores 2 5)
  putStrLn (compareScores 4 4)
bagel: 2.5
tea: not on the menu
won by 2
lost by 3
draw

Matching on a tuple of values lets one case look at two things at once.

Guards inside case

Each alternative can have guards. They are tested after the pattern matches:

haskell · try it yourself
bmiAdvice :: Maybe Double -> String
bmiAdvice reading = case reading of
  Nothing -> "no reading"
  Just bmi
    | bmi < 18.5 -> "underweight"
    | bmi < 25 -> "healthy"
    | otherwise -> "overweight"

main :: IO ()
main = mapM_ (putStrLn . bmiAdvice) [Just 17.2, Just 22.0, Just 31.4, Nothing]
underweight
healthy
overweight
no reading

Notice that inside case the guards use ->, while in function equations they use =.

Equations are sugar for case

These two definitions are exactly the same function. GHC turns the first form into the second:

haskell · try it yourself
lengthA :: [a] -> Int
lengthA [] = 0
lengthA (_ : rest) = 1 + lengthA rest

lengthB :: [a] -> Int
lengthB xs = case xs of
  [] -> 0
  (_ : rest) -> 1 + lengthB rest

main :: IO ()
main = print (lengthA "abcd", lengthB [True, False])
(4,2)

Use equations when the function's logic is "one answer per input shape", and case when you match on an intermediate result or only part of a function needs a decision.

\case: the lambda-case shortcut

A function that immediately does case on its argument can use the \case syntax. It comes from the LambdaCase language extension, which you switch on with a pragma at the very top of the file (GHC 9.12 compiles in the GHC2021 language edition, which doesn't include it):

haskell · try it yourself
{-# LANGUAGE LambdaCase #-}

main :: IO ()
main = do
  let signName = \case
        0 -> "zero"
        n | n > 0 -> "positive"
          | otherwise -> "negative"
  mapM_ (putStrLn . signName) [5, 0, -3 :: Int]
positive
zero
negative

Note: A case with a missing alternative crashes at run time when that value appears ("Non-exhaustive patterns in case"). End with a _ -> alternative, or match every constructor.

Test yourself

What is the result type of a case expression whose alternatives return "yes" and "no"?

  1. Bool
  2. String
  3. IO ()
  4. It has no type

What does case [3, 4] of { [] -> 0; (x : _) -> x } return?

  1. 0
  2. 3
  3. 4
  4. [3,4]

In a case alternative, guards are followed by which symbol?

  1. =
  2. ->
  3. =>
  4. :