Skip to content

Instantly share code, notes, and snippets.

@mdales
Created September 8, 2022 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdales/1c84f449d49000406aab3296342a3a9f to your computer and use it in GitHub Desktop.
Save mdales/1c84f449d49000406aab3296342a3a9f to your computer and use it in GitHub Desktop.
Now with arrays
#!/usr/bin/env python3
class Foo:
def __init__(self, lhs, op=None, rhs=None):
self.lhs = lhs
if op: self.op = op
if rhs:
if len(lhs) != len(rhs):
raise ValueError("Mismatched array sizes")
self.rhs = rhs
def __str__(self):
try:
return f"({self.lhs} {self.op} {self.rhs})"
except AttributeError:
return str(self.lhs)
def __add__(self, other):
return Foo(self, "__add__", other)
def __sub__(self, other):
return Foo(self, "__sub__", other)
def __mul__(self, other):
return Foo(self, "__mul__", other)
def __truediv__(self, other):
return Foo(self, "__truediv__", other)
def __len__(self):
return len(self.lhs)
def eval(self, index=None):
try:
if index is not None:
return getattr(self.lhs.eval(index), self.op)(self.rhs.eval(index))
else:
return [
getattr(self.lhs.eval(idx), self.op)(self.rhs.eval(idx))
for idx in range(len(self))]
except AttributeError:
try:
return self.lhs[index]
except TypeError:
return self.lhs
a = Foo([42.0, 34.0])
b = Foo([7.0, 2.0])
c = (a + b) / b
print(c)
print(c.eval())
c = a + (b / b)
print(c)
print(c.eval())
@mdales
Copy link
Author

mdales commented Sep 8, 2022

This version works with arrays, and should never hold intermediary values in the expression as arrays in memory

Output:

$ ./arraytest.py
(([42.0, 34.0] __add__ [7.0, 2.0]) __truediv__ [7.0, 2.0])
[7.0, 18.0]
([42.0, 34.0] __add__ ([7.0, 2.0] __truediv__ [7.0, 2.0]))
[43.0, 35.0]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment