Haskell Pattern Matching Guide — Destructuring Data with Patterns
In this tutorial, you will learn about Haskell Pattern Matching Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Haskell pattern matching is a fundamental control flow mechanism that destructures data by matching values against patterns -- used in function definitions, case expressions, and list processing with compiler-verified exhaustiveness.
Function Pattern Matching
-- Match on list patterns
sumList :: [Int] -> Int
sumList [] = 0
sumList (x:xs) = x + sumList xs
-- Match on Maybe
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (x `div` y)
-- Match on Bool
not' :: Bool -> Bool
not' True = False
not' False = True
Case Expressions
describeMaybe :: Maybe Int -> String
describeMaybe mx = case mx of
Nothing -> "No value"
Just n -> "Got: " ++ show n
Pattern Types
-- Wildcard pattern
first :: [a] -> a
first (x:_) = x
first _ = error "empty list"
-- As pattern
fullName :: String -> String
fullName name@(first:' ':rest) =
"Name: " ++ name ++ ", First: " ++ [first]
fullName _ = "Invalid"
-- Literal patterns
isOne :: Int -> Bool
isOne 1 = True
isOne _ = False
Guards with Patterns
classify :: Int -> String
classify n
| n < 0 = "Negative"
| n == 0 = "Zero"
| n > 0 = "Positive"
Common Mistakes
1. Incomplete patterns
GHC warns with -Wall about non-exhaustive patterns. Always cover all constructors.
2. Overlapping patterns
Patterns are matched top-to-bottom. Put specific cases before general ones.
3. Wrong order in (x:xs)
(x:xs) matches head and tail. [] matches empty list. (x:y:zs) matches first two elements.
Practice Questions
1. What order are patterns evaluated? Top to bottom. The first matching pattern is used.
2. What does _ mean in a pattern?
Wildcard -- matches anything but doesn't bind a name.
3. How do you match an empty list?
[] pattern matches the empty list. (x:xs) matches non-empty.
FAQ
{{< faq question="Can I use pattern matching with guards together?" >}}
Yes. Define function clauses with patterns, then add guards: max' a b | a >= b = a | otherwise = b.
{{< /faq >}}
{{< faq question="What happens if no pattern matches?" >}} At compile time, GHC warns about non-exhaustive patterns. At runtime, it raises a pattern match failure exception. {{< /faq >}}
{{< faq question="Can I match on the same value multiple times?" >}}
Yes, pattern matching is linear -- each variable appears at most once per pattern (unless using _). Use guards for repeated comparisons.
{{< /faq >}}
What's Next
Now learn about lists in Haskell.
| Topic | Description | Link |
|---|---|---|
| Lists | Working with linked lists | {{< ref "06-lists" >}} |
| Recursion | Recursive functions | {{< ref "07-recursion" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro