Sobes.tech
Middle+

What is the Interpreter design pattern?

sobes.tech AI

Answer from AI

The Interpreter pattern is used to define a grammatical representation of a language and provides an interpreter to process sentences in that language.

Key elements:

  • Abstract Syntax Tree (AST): A data structure representing a language sentence.
  • AbstractExpression: An interface or abstract class for all AST nodes. It defines the interpret() operation.
  • TerminalExpression: A concrete class implementing AbstractExpression for terminal symbols of the grammar.
  • NonterminalExpression: A concrete class implementing AbstractExpression for non-terminal symbols of the grammar. It usually contains references to other expressions.
  • Context: Stores information used during interpretation.

Application:

  • When it is necessary to analyze and interpret expressions in a simple language.
  • When the language grammar is relatively simple.

Advantages:

  • Simplifies adding new ways to interpret expressions.
  • Easy to extend the grammar.

Disadvantages:

  • Can become difficult to manage for complex grammars.
  • Creating an AST can be costly.

Example: A simple grammar for arithmetic expressions (addition and subtraction)

# Abstract Expression
class AbstractExpression:
    def interpret(self, context):
        pass

# Terminal Expression (Numbers)
class NumberExpression(AbstractExpression):
    def __init__(self, value):
        self.value = value

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

# Nonterminal Expression (Addition)
class AddExpression(AbstractExpression):
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def interpret(self, context):
        return self.left.interpret(context) + self.right.interpret(context)

# Nonterminal Expression (Subtraction)
class SubtractExpression(AbstractExpression):
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def interpret(self, context):
        return self.left.interpret(context) - self.right.interpret(context)

# Context (not needed in this case, but can be used for variables, etc.)
class Context:
    pass

# Usage example
# Creating AST for the expression "5 + (3 - 2)"
ast = AddExpression(
    NumberExpression(5),
    SubtractExpression(NumberExpression(3), NumberExpression(2))
)

context = Context()
result = ast.interpret(context)
print(result) # Output: 6