Comparison Terminal

Step 4 - Comparison Terminal: Equals

Real rule engines compare fields, not just booleans. Add a comparison leaf.

  • Equals(key, value).interpret(context) returns True when context.get(key) equals value, otherwise False. A missing key compares against None, so it returns False unless value is also None.

This lets you write rules like country equals US.

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

    def interpret(self, context):
        return bool(context.get(self.name, False))


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

    def interpret(self, context):
        return self.value


class And:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def interpret(self, context):
        return self.a.interpret(context) and self.b.interpret(context)


class Or:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def interpret(self, context):
        return self.a.interpret(context) or self.b.interpret(context)


class Not:
    def __init__(self, expr):
        self.expr = expr

    def interpret(self, context):
        return not self.expr.interpret(context)


class Equals:
    def __init__(self, key, value):
        self.key = key
        self.value = value

    def interpret(self, context):
        """Return True when context[key] equals value, else False."""
        # TODO: return context.get(self.key) == 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.