git.haldean.org symrep / 19aac26
make sum/product take varargs Will Haldean Brown 6 years ago
2 changed file(s) with 15 addition(s) and 6 deletion(s). Raw diff Collapse all Expand all
0 import operator
1
2
03 def const(val):
14 return Node("const {}".format(val), lambda _: val, [])
25
3 def sum(n1, n2):
4 return Node("add", lambda t: n1(t) + n2(t), [n1, n2])
6 def sum(*nodes):
7 return Node(
8 "sum",
9 lambda t: reduce(operator.add, (n(t) for n in nodes), 0),
10 nodes)
511
6 def product(n1, n2):
7 return Node("product", lambda t: n1(t) * n2(t), [n1, n2])
12 def product(*nodes):
13 return Node(
14 "product",
15 lambda t: reduce(operator.mul, (n(t) for n in nodes), 1),
16 nodes)
817
918 class Node(object):
1019 _next_id = 0
1616 n = symrep.sum(n1, n2)
1717 self.assertEqual(n(0), 3)
1818
19 n = symrep.sum(n1, n1)
20 self.assertEqual(n(0), 2)
19 n = symrep.sum(n1, n1, n1)
20 self.assertEqual(n(0), 3)
2121
2222 def test_product(self):
2323 n = symrep.product(symrep.const(1), symrep.const(-3))