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

42

Comments

  1. Each token has its own method. a and b each turn their match into an integer with make $/.Int.

  2. The TOP method does not re-convert the text; it reads the values the sub-methods already made, with $<a>.made and $<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