ericlippert.com - Fabulous adventures in coding | Eric Lippert's blog

Description: Eric Lippert's blog

Example domain paragraphs

I wanted to implement concise “pattern matching” in Python, a language which unlike C#, F#, Scala, and so on, does not have any pattern matching built in. Logically a pattern is just a predicate: a function which takes a value and returns true if the value “matches” the pattern, false otherwise. The code for this episode is here .

When I embarked on this I realized two things. First, that it might be nice for debugging purposes to have more information in the return value than just “true” or “false”; in particular, when a complex pattern fails to match, but it should match, then I’ve made a mistake. In order to debug that mistake, I actually made patterns return a new type:

class MatchResult(ABC): test: Any submatches: Dict[str, "MatchResult"] # ... and so on, boilerplate code for the rest of this. A complex pattern might fail because of its component patterns failing to match, and so that information is included in the failure result. I also made subclasses Success and Fail .

Links to ericlippert.com (21)