Add multiplication. Mul is a new node just like Add: it holds a left and a right child, and its accept routes to a new visit method, visit_mul.
Now trees can mix operators, like Add(Num(2), Mul(Num(3), Num(4))), and the same EvalVisitor walks them correctly.
class Num:
def __init__(self, value):
self.value = value
def accept(self, visitor):
return visitor.visit_num(self)
class Add:
def __init__(self, left, right):
self.left = left
self.right = right
def accept(self, visitor):
return visitor.visit_add(self)
class Mul:
def __init__(self, left, right):
self.left = left
self.right = right
def accept(self, visitor):
"""Dispatch to the visitor method for a Mul node."""
# TODO: return visitor.visit_mul(self)
pass
class EvalVisitor:
def visit_num(self, node):
return node.value
def visit_add(self, node):
return node.left.accept(self) + node.right.accept(self)
def visit_mul(self, node):
"""Return the product of evaluating both children."""
# TODO: return node.left.accept(self) * node.right.accept(self)
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Add multiplication. Mul is a new node just like Add: it holds a left and a right child, and its accept routes to a new visit method, visit_mul.
Now trees can mix operators, like Add(Num(2), Mul(Num(3), Num(4))), and the same EvalVisitor walks them correctly.
Press Run Tests or ββ© to check your solution.