Interpreter Pattern

The Interpreter pattern: representing each rule of a small language as a class, evaluating a sentence as a tree of those objects, and knowing that parsing is a separate job.

  • 8 cards
  • 4 questions
  • About 14 min
  • Intermediate to Advanced
Share

Some programs need a small language of their own: discount rules such as "total over 100 and member", search filters, or formulas in a spreadsheet cell. Evaluating them by cutting up strings works for the first rule and breaks on the first nested one. The Interpreter pattern makes each rule of the language a class, so that a sentence becomes a tree of objects that evaluates itself.

This topic opens on that problem, then reads the participants off the class diagram and matches them to the rules of a grammar, sorting terminal expressions, the leaves, from non-terminal ones, which combine others. The template evaluates 1 + 2 * x in three languages.

Two examples follow: discount rules evaluated against a basket, and Python's own ast module, which turns 1 + 2 * 3 into the same kind of tree. The gotcha is what the pattern leaves out, turning text into the tree, and the exercise sorts and evaluates the classes of a small boolean language.

By the end you can recognise an interpreter, write one for a small grammar, and tell the leaves of its tree from the nodes that combine them.

Contents

8 cardsnot started