Lesson 09 of 55
10 mins readPython Pattern Matching on Functions
In Plain English
Pattern matching checks values against data shapes. Deconstruct lists with (x:xs), match literal constants (0, "text"), or ignore values with wildcard (_).
Deep Dive: How It Works
Literal Patterns: factorial 0 = 1 specifies the base case explicitly.
List Deconstruction (x:xs): Matches the head element x and tail sublist xs.
Wildcard (_): Matches and ignores any argument value without binding it.
Exhaustiveness: The compiler warns if patterns do not cover all possible inputs.
Core Rules to Remember

Declarative Base Cases: Define mathematical base and recursive cases as separate equation lines.

(x:xs) Deconstruction: Unpack the first item and remaining list elements with zero boilerplate.
Live Interactive Example
Hit Run Code to see it liveRecursive Factorial and List Sum with Patterns
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: factorial matches 0 then n. sumList matches [] then (x:xs).
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Calculate List Length with Pattern Matching
Define `myLength [] = 0` and `myLength (_:xs) = 1 + myLength xs`.
Print `"Length: "` followed by `show (myLength [10, 20, 30])`.
1
2
3
4
5
6
7
8
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.