Terminal Expressions

Step 1 - Terminal Expressions

The Interpreter pattern represents a grammar as a tree of expression objects. Every expression exposes one method: interpret(context), where context is a dict acting as the environment.

Implement the two terminal (leaf) expressions:

  • Var(name).interpret(context) returns the boolean value stored under name in the context. If the key is missing, return False.
  • Const(value).interpret(context) returns its fixed value, ignoring the context.

These leaves are the foundation the rest of the grammar builds on.

Hints
Starter code
class Var:
    def __init__(self, name):
        self.name = name

    def interpret(self, context):
        """Return the boolean value stored under name, or False if missing."""
        # TODO: look up self.name in context, defaulting to False, return a bool
        pass


class Const:
    def __init__(self, value):
        self.value = value

    def interpret(self, context):
        """Return the fixed value, ignoring the context."""
        # TODO: return self.value
        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.