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
12Comments
<number>+ % '+'matches one or more numbers separated by+signs — the%modifier describes the separator between repetitions.The action method runs when
TOPmatches.makeattaches a computed value — the sum of the numbers — which.madereads back after parsing.