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...