I want to implement a new type of expression so that, given:
import sympy
class MyExpr(sympy.Expr,...):
...
a,b,c,x = sympy.symbols('a b c x')
e1 = MyExpr(a,b,c)
e2 = MyExpr(b,c)
this would be so:
e1.subs(e2,x) == MyExpr(a,x)
I need a new kind of operation because I'm not working with numbers and need a very specific set of operations. MyExpr needs to be associative but not commutative.
So far I have basically this (I'm working with Python 3):
class MyExpr(sympy.Expr):
@sympy.cacheit
def __new__(cls,*args):
tmp = []
for a in args:
a = sympy.sympify(a,strict=True)
if type(a) is cls:
tmp.extend(a.args)
else:
tmp.append(a)
return super().__new__(cls,*tmp)
is_commutative = False
What do I need for the above to work? I looked at the source for
sympy.Add and some other classes and figure I need to implement
match() and compare contiguous slices, but the implementation for
Add.match is far from straight-forward.