[Python-ideas] Symbolic expressions (or: partials and closures from the inside out)
Carl M. Johnson
cmjohnson.mailinglist at gmail.com
Sat Jan 14 07:27:35 CET 2012
You guys know this can more or less be done in Python today, right?
>>> class Symbolic:
... def __init__(self, func=lambda x: x):
... self.func = func
...
... def __call__(self, arg):
... return self.func(arg)
...
... def __add__(self, other):
... func = lambda x: self.func(x) + other
... return Symbolic(func)
...
... __radd__ = __add__
...
... def __mul__(self, other):
... func = lambda x: self.func(x) * other
... return Symbolic(func)
...
... __rmul__ = __mul__
...
>>>
>>> X = Symbolic()
>>> Y = (2 * X) + 10
>>> Y(20)
50
I leave further extensions as an exercise for the reader, but it's not especially tricky to add various boolean tests and whatnot.
I don't claim any originality here. I'm fairly sure I read about this idea in blog post somewhere years ago.
More information about the Python-ideas
mailing list