Course of Raku / Regexes and grammars / Grammars / Action classes / Exercises / A multiply action
Solution: A multiply action
Here is a possible solution to the task.
Code
grammar Mul {
token TOP { <a> '*' <b> }
token a { \d+ }
token b { \d+ }
}
class MulActions {
method a($/) { make $/.Int }
method b($/) { make $/.Int }
method TOP($/) { make $<a>.made * $<b>.made }
}
say Mul.parse('6*7', actions => MulActions.new).made;🦋 You can find the source code in the file multiply-action.raku.
Output
42Comments
Each token has its own method.
aandbeach turn their match into an integer withmake $/.Int.The
TOPmethod does not re-convert the text; it reads the values the sub-methods already made, with$<a>.madeand$<b>.made, and makes their product. The value is built from the bottom up — which is how action classes scale to larger grammars.
Course navigation
← A multiply action | Functional, concurrent, reactive, and web programming →