I have implemented an illustratory pattern matching library decorator for Python. Just download matcher.py and play with it yourself.
What can I do with it?
You can do basic pattern matching for simple values. The following example shows you what you can do with lists.
from pattern_matching import *
@pattern_matching
def print_list(a_list)
"""prints a list, element by element"""
@print_list.dispatch(lst[_:_])
def _at_least_one(a_list):
print a_list[0]
print_list(a_list)
@print_list_dispatch([])
def _empty_list(a_list)
print "done!"
The lst variable is a special one and is used for using Haskell-like syntax on Python, the slice object represents head and tail of a list. The _ variable represents the any element, just like on the other language too.
Note: This is just an example of what you can do with decorators, it’s not supposed to be a multi-dispatch library, if you want one use the excelent dispatch module.
3 comments:
That's clever, but it seems to make the code unreadable and un-pythonic (actually, unreadable code is un-pythonic by definition).
Pattern matching is an interesting feature of functional languages, but I doubt its usefulness in a language like Python.
If you think about pattern matching as a domain specific language then it is normal that, out of its domain, it is regarded as "unreadable", yet within its context shouldn't :P
If you want to see what sort of interesting stuff can be done with pattern matching in Python you should check out PJE's RuleDispatch package (part of the PEAK framework, but RuleDispatch can be used without the rest of the framework...)
Post a Comment