🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Pattern Matching

Pattern matching is a way for a function to choose an equation by the pattern its argument fits. Haskell tries the equations from top to bottom.

Literal patterns match exact values

Each equation starts with a different pattern. The argument 1 matches the second equation.

describe 0 = "Zero"
describe 1 = "One"
describe _ = "Other"
main :: IO ()
main = putStrLn (describe 1)

[x] matches a one-item list

The pattern [x] matches a list with exactly one item. The name x stands for that item.

onlyItem [x] = x
onlyItem _ = 0
main :: IO ()
main = print (onlyItem [9])

x:xs names the first item and the rest

The pattern [] matches an empty list. The pattern x:xs names the first item x and the rest xs.

firstItem [] = 0
firstItem (x:xs) = x
main :: IO ()
main = print (firstItem [7, 8])

Example

sizeLabel [] = "Empty"
sizeLabel [_] = "One"
sizeLabel _ = "Many"
main :: IO ()
main = putStrLn (sizeLabel [3, 9])

Key points

  • Pattern: a pattern describes a value that an equation can match.
  • Equation: an equation pairs one pattern with one result.
  • Order: Haskell tries the equations from top to bottom.
  • Literal pattern: a literal pattern matches only that exact value.
  • Variable pattern: a variable pattern matches any value and gives it a name.
  • Wildcard: the wildcard _ matches any value without naming it.

In this example, sizeLabel tries the empty pattern first and it does not match, the one-item pattern does not match either, and the wildcard equation gives Many for the two-item list.

Note

a list pattern can name the first item and the rest with x:xs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does putStrLn (label [8]) print for a function whose equations label [] as Empty, [x] as One, and anything else as Many?