Zachary W. Huang

Home Projects Blog Guides Resume

Interpreter

Idea: Specify a simple language along with an interpreter to execute code written in this language. For example, regular expressions are a custom language that make it easier to specify how to match text to a specification.

Note: the tree structure walked/executed by an interpreter is typically known as an abstract syntax tree (AST).

Connection: Greenspun’s tenth law

Below is a simple expression language and interpreter.

abstract class Expression {
  abstract interpret();
}

class Literal extends Expression {
  value: number

  constructor(value: number) {
    super();
    this.value = value;
  }

  interpret() {
    return this.value;
  }
}

class Add extends Expression {
  left: Expression;
  right: Expression;

  constructor(left: Expression, right: Expression) {
    super();
    this.left = left;
    this.right = right;
  }

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

class Multiply extends Expression {
  left: Expression;
  right: Expression;

  constructor(left: Expression, right: Expression) {
    super();
    this.left = left;
    this.right = right;
  }

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

function main() {
  const expr = new Add(new Multiply(new Literal(2), new Literal(3)), new Literal(1))
  console.log(expr.interpret()); // "7"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024