behavioral

Interpreter

Represent grammar rules as objects and interpret sentences by evaluating an abstract syntax tree or expression chain.

Problem

behavioral

You need to define a small language or expression grammar and evaluate it consistently across the application.

Integration notes

Interpreter is useful for calculators, rule engines, simple DSLs, and command parsing systems where a structured grammar must be evaluated.

Tradeoffs

  • Can become complex if the grammar grows too large.
  • Best suited to small, well-defined languages or expression sets.

Languages

typescript, java, python, angular, react, react-native, csharp, dotnet

Platforms

Web, Backend, Mobile, UI kits, Cross-platform systems

Variants

Scenarios

Expression interpreter

An arithmetic expression is represented as a tree of terminal and non-terminal expressions and then evaluated.

Language examples

Core languages

Frameworks and libraries

Expression interpretertypescript

The expression interpreter builds an object tree for the grammar and evaluates it by calling interpret() from the root node.

TypeScript
interface Expression {
  interpret(): number;
}


class NumberExpression implements Expression {
  constructor(private value: number) {}


  interpret(): number {
    return this.value;
  }
}


class AddExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}


  interpret(): number {
    return this.left.interpret() + this.right.interpret();
  }
}


class SubtractExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}


  interpret(): number {
    return this.left.interpret() - this.right.interpret();
  }
}


class MultiplyExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}


  interpret(): number {
    return this.left.interpret() * this.right.interpret();
  }
}


const expression = new SubtractExpression(
  new AddExpression(new NumberExpression(5), new NumberExpression(3)),
  new MultiplyExpression(new NumberExpression(2), new NumberExpression(4))
);


console.log(expression.interpret());

Real-world examples

  • Calculator apps: Simple calculators interpret expressions like addition, subtraction, and grouping.
  • Rule engines: Applications often evaluate rule expressions such as access conditions or eligibility checks.
  • Command parsing: CLI tools and DSLs interpret user commands into executable actions.