A New Node Type

Step 3: A New Node Type

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.

  • Mul.accept(visitor) returns visitor.visit_mul(self)
  • EvalVisitor.visit_mul(node) returns node.left.accept(self) * node.right.accept(self)

Now trees can mix operators, like Add(Num(2), Mul(Num(3), Num(4))), and the same EvalVisitor walks them correctly.

Hints
Starter code
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)
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.