Lesson 10 of 55
9 mins readPython Case Expressions (case of)
In Plain English
While function pattern matching happens at function definition headers, case expressions allow matching data shapes anywhere inside arbitrary expressions.
Deep Dive: How It Works
case Syntax: case expression of pattern1 -> result1; pattern2 -> result2.
Syntactic Equivalence: Pattern matching in function arguments is syntactic sugar for a top-level case expression.
Core Rules to Remember

Inline Pattern Matching: Match on intermediate computed values anywhere in your code.

Uniform Types: All branches of a case expression must evaluate to the same return type.
Live Interactive Example
Hit Run Code to see it liveDescribing Lists with Case Expressions
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: case matches empty [], single [_], and catch-all _.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Inspect First Element with Case
Define `firstOrZero list = case list of [] -> 0; (x:_) -> x`.
Print `"First: "` followed by `show (firstOrZero [99, 100])`.
1
2
3
4
5
6
7
8
9
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.