🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Case Expressions

A case expression is a choice that matches a value against several patterns. Each pattern is tried in order, and the first match gives the result.

Literal patterns match exact values

The function matches its input against 1 and then 2. The input 2 matches the second alternative.

dayName day =
  case day of
    1 -> "Monday"
    2 -> "Tuesday"
    _ -> "Other day"

main :: IO ()
main = putStrLn (dayName 2)

A list pattern can name the item inside

The pattern [x] matches a list with exactly one item and names it x. The result is that item, 7.

singleValue items =
  case items of
    [] -> 0
    [x] -> x
    _ -> 99

main :: IO ()
main = print (singleValue [7])

A tuple pattern names both parts

The pattern (x, y) matches the pair and names its two numbers. The result adds them.

sumPair pair =
  case pair of
    (x, y) -> x + y

main :: IO ()
main = print (sumPair (4, 6))

Example

dayName day =
  case day of
    1 -> "Monday"
    2 -> "Tuesday"
    _ -> "Another day"

listLabel items =
  case items of
    [] -> "empty"
    [x] -> "single"
    _ -> "many"

main :: IO ()
main = putStrLn (dayName 1 ++ " - " ++ listLabel [9, 8])

Key points

  • Case expression: a choice that matches a value against several alternatives in order.
  • of: the word of after the value starts the list of alternatives.
  • Alternative: one line of a case, with a pattern, an arrow and a result.
  • Literal pattern: a pattern such as 1 matches only that exact value.
  • Wildcard: the pattern _ matches any value, so it works as a catch-all.
  • List and tuple patterns: patterns such as [x] and (x, y) match the shape of a value and name its parts.

In this example, dayName matches 1 and gives Monday. listLabel then matches a two-item list, which falls past the empty and one-item patterns to the wildcard, giving many.

Note

alternatives are tried from top to bottom, so a catch-all placed first would match everything.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

In a case expression, the value 3 is matched against 1, then 2, then _. Which result is picked, if the three results are "One", "Two" and "Other"?