Repetition
Since we can use the result of an addition in another addition, we can theoretically add any amount of numbers together. This is not a very nice way of dealing with the problem.
> add 1 add 2 add 3 add 4 5
15
Instead we can use Repeat
which evaluates to an array of of its inner type.
Func("sum")
.arg(new Repeat(value))
.setExec((args: number[]) => args.reduce((sum, next) => sum + next, 0)),
> sum 1 2 3 4 5
15
> sum
0
> sum 1 2 3 mul 4 5
26
> mul 2 sum 3 4 5
24
> mul sum 3 4 5 2
Error: Parser finished but expected type <t.value>.
Notice how the last example didn't work. This is because Repeat
parses until the end of input is reached, meaning the 2
is consumed by sum
and not given as an argument to mul
. This can also be seen in the grammar. We fix this in the next chapter.
l.calc:
| <t.value> EOI
t.value:
| "add" <t.value> <t.value>
| "mul" <t.value> <t.value>
| "sum" <r.t.value>
| "pi"
| <p.number>
r.t.value:
| <t.value> * EOI