Guarded Patterns (if conditions in match)
1Concept
A guard clause (`if boolean_condition`) can be appended to any case pattern. The case succeeds ONLY if both the pattern structure matches AND the guard expression evaluates to True.
2Architecture Diagram
case [x, y] if x == y: ---> Matches 2-element sequence where both elements are equal!
3Code Example
Python 3.12
def categorize_number(val):
match val:
case int(n) if n > 0 and n % 2 == 0:
return f"Positive Even Integer: {n}"
case int(n) if n > 0:
return f"Positive Odd Integer: {n}"
case int(n) if n < 0:
return f"Negative Integer: {n}"
case _:
return "Zero or Non-Integer"
print(categorize_number(42))
print(categorize_number(-15))4Expected Output
Positive Even Integer: 42 Negative Integer: -15
5Key Takeaways
- ✓Variables bound in the pattern are accessible inside the `if` guard condition.
- ✓If the guard fails, matching continues to subsequent `case` branches.
- ✓Guards prevent deep nested if-checks inside pattern matching blocks.