Combine OR and AS Patterns
Core idea
An OR pattern uses | between alternatives. The alternatives must bind the same set of names, and the first successful alternative wins. An AS pattern attaches as name to a pattern to retain the whole value matched by that pattern. There is no general AND pattern operator; nested patterns or guards express multiple requirements.
match "pause": case "stop" | "pause": print("hold") case _: print("other")Either literal selects the same case.
Capture a field in either shape
match ["out", 5]: case ["in", n] | ["out", n]: print(n)Both alternatives bind n, so the case can use it regardless of which matched.
Keep the original event
match ("in", 4): case ("in", n) as event: print(n, event)n is the second item; event is the complete tuple.
Common mistake
case ["in", a] | ["out", b]: is invalid because the alternatives bind different names. Use the same capture name in both or separate cases.
Practice
Match either "red" or "amber" and use as to print the original color. Add an unmatched color to your tests.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Combine alternatives and captures
Check your understanding of or and as patterns.
What is printed?
match "pause": case "stop" | "pause": print("hold") case _: print("go")What is printed?
match ["out", 4]: case ["in", n] | ["out", n]: print(n)What is printed?
match ["in", 4]: case ["in", n] as item: print(len(item))What is required of names bound by alternatives in an OR pattern?