Course of Raku / Addendum 🆕 / Types and text machines / Regexes and grammars / Exercises / A grammar that adds

Solution: A grammar that adds

Here is a possible solution to the task.

Code

grammar Sum {
    token TOP    { <number>+ % '+' }
    token number { \d+ }
}

class SumActions {
    method TOP($/) { make [+] $<number>.map(*.Int) }
}

say Sum.parse('3+4+5', actions => SumActions).made;

🦋 You can find the source code in the file grammar-sum.raku.

Output

12

Comments

  1. <number>+ % '+' matches one or more numbers separated by + signs — the % modifier describes the separator between repetitions.

  2. The action method runs when TOP matches. make attaches a computed value — the sum of the numbers — which .made reads back after parsing.

Course navigation

A grammar that adds   |   Bringing it together