Skip to main content

What It Is

The Interpreter pattern evaluates sentences in a small language by building a tree of expression objects — each node knows how to interpret itself. Numbers interpret to themselves; an addition node interprets its two sides and adds them.

It fits small languages: filters, formulas, simple rules. Real languages deserve real parser tools.


Example: A Tiny Calculator

The input 3 + 4 - 2 becomes a tree of Number, Add and Subtract nodes. One call to Interpret() on the root evaluates the whole expression.

Every node interprets itself

parse builds the tree left to right; Interpret() walks it. Supporting * would be one new node type — the existing ones stay untouched.

Prompt
Write a Go program with the Interpreter pattern: an Expression interface with Interpret, Number, Add and Subtract nodes, and a parse function that turns a string like "3 + 4 - 2" into an expression tree left to right. Interpret the expression and print the equation with its result.
Output: Go program and captured output

When to Use It

Use it when users or configs express logic in a small language of your design: search filters, pricing formulas, validation rules.

Skip it when the "language" is three fixed options (use a switch) — or a real language (use a parser generator or an existing engine).


Pros and Cons

Pros: the grammar maps one-to-one onto small types; new operations are new node types; expression trees can be built, checked and reused.

Cons: grows painful as the grammar grows; parsing itself still has to be written; performance is modest compared to compiled logic.