Python Pattern Matching?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
4 views
I love writing in Python. Decided, as they say, just for fan, to make in Python something like a simple Pattern Matching in the style of Erlang (as recently started erlang, and penetrated)). There is one problem. Don't know how to do it nicely, so that it is pythonic. ) Does not come up with anything better than something like this:
class PFPM(object): def __init__(self, name): self._name = name self._clauses = [] self._cur = 0 def __call__(self, *fpars): # parse, execute, return None #and return result def match(self, *pars): self._clauses.append({"match": pars}) self._cur += 1 return self def where(self, guard): self._clauses[self._cur]["guard"] = guard return self def func(self, *exprs): self._clauses[self._cur]["funcs"] = exprs return self def max_of_list(numlist): fmax = PFPM("fmax") # Next, how it all looks: fmax.match("[H|T]").func("fmax(T,H)") fmax.match("[H|T]","N").where("H>N").func("fmax(T,H)") fmax.match("[_|T]","N").func("fmax(T,N)") fmax.match("[]","X").func("X") return fmax(numlist) print max_of_list([3,1,2,6,4,5])



can anyone tell me, will offer more than the "sugar" way...
by | 4 views

3 Answers

0 like 0 dislike
by
0 like 0 dislike
sugar way to choose another language, where pattern matching is already implemented. the solution with strings *I think* has no practical value.
\r
by the way in Python is tuple unpacking, which is usually enough for the needs of ordinary mortals.
by
0 like 0 dislike
Also dabbled in this direction, here's what happened:
\rgithub.com/Suor/patterns
\r
Sugar is achieved by restructuring the AST of the decorated function.
by

Related questions

0 like 0 dislike
3 answers
0 like 0 dislike
1 answer
0 like 0 dislike
4 answers
0 like 0 dislike
4 answers
0 like 0 dislike
4 answers
110,608 questions
257,186 answers
0 comments
27,978 users