Example: Calculator

In this chapter we will incrementally build up a basic calculator. As a starting point we trivially adapt the language greet from the previous chapter, into the language calc.

const value = new Type<number>("value");

value.setFunctions([
  Func("add")
    .arg(primitives.number)
    .arg(primitives.number)
    .setExec((left, right) => left + right),
  Func("mul")
    .arg(primitives.number)
    .arg(primitives.number)
    .setExec((left, right) => left * right),
  Constant("pi", () => 3.14),
]);

const calc = new Language("calc", value);

This language has the following grammar:

l.calc:
 | <t.value> EOI

t.value:
 | "add" <p.number> <p.number>
 | "mul" <p.number> <p.number>
 | "pi" 

Running the language like before gives:

> add 1 5
6
> mul 9 5
45
> pi
3.14