The Eval Visitor

Step 2: The Eval Visitor

Now add the first real operation as a visitor object. EvalVisitor turns a tree into a number.

Because accept already routes each node to the right method, the visitor just fills in behavior:

  • visit_num(node) returns node.value
  • visit_add(node) returns node.left.accept(self) + node.right.accept(self)

Notice the recursion: to evaluate an Add, you ask each child to accept the same visitor. The node classes stay untouched. The whole operation lives in one visitor.

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 EvalVisitor:
    def visit_num(self, node):
        """Return the numeric value of a Num node."""
        # TODO: return node.value
        pass

    def visit_add(self, node):
        """Return the sum 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.