Google News
logo
Haskell - Interview Questions
How does pattern matching work in Haskell?
Pattern matching is a powerful feature in Haskell that allows you to destructure data and control flow based on the shape and contents of values. It is used extensively in function definitions, case expressions, and let bindings. Pattern matching works as follows in Haskell:

1. Function Definitions : When defining a function in Haskell, you can use pattern matching to specify different behavior for different patterns of input values. Each function definition can have multiple equations, each with a different pattern and corresponding implementation.

For example, consider a function to calculate the factorial of a number:
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)​

In this example, the first equation matches the pattern `0`, and it returns `1`. The second equation matches any non-zero value `n`, and it recursively calculates the factorial by multiplying `n` with the factorial of `(n - 1)`.


2. Case Expressions : Pattern matching is commonly used in case expressions to handle different cases or branches based on the pattern of a value. Case expressions provide a way to perform pattern matching and define different actions for different patterns.

For example, consider a function that converts a day of the week into its corresponding number:
dayToNumber :: String -> Int
dayToNumber day = case day of
  "Monday"    -> 1
  "Tuesday"   -> 2
  "Wednesday" -> 3
  "Thursday"  -> 4
  "Friday"    -> 5
  "Saturday"  -> 6
  "Sunday"    -> 7
  _           -> error "Invalid day"​
In this example, the case expression matches the value of `day` against different patterns (day names) and returns the corresponding number. The underscore `_` serves as a catch-all pattern that matches any value and indicates an error for invalid inputs.


3. List Patterns : Pattern matching can be used to extract elements from lists. You can match against specific values, patterns, or use syntactic sugar like the cons operator `:` to match against the head and tail of a list.

For example, consider a function to compute the sum of a list:
sumList :: [Int] -> Int
sumList []     = 0
sumList (x:xs) = x + sumList xs​

In this example, the first equation matches an empty list `[]` and returns `0`. The second equation matches a non-empty list `(x:xs)` by binding the head `x` and the tail `xs`. It recursively calculates the sum by adding the head with the sum of the tail.

Pattern matching in Haskell is a powerful mechanism that allows you to concisely and elegantly express computations based on the structure and content of data. It promotes readable code, simplifies branching logic, and enables the manipulation of complex data structures.
Advertisement