Course of Raku / Regexes and grammars / Grammars / The parse tree, make and made / Exercises / Multiply a pair

Solution: Multiply a pair

Here is a possible solution to the task.

Code

grammar Product {
    token TOP { <a> '*' <b> { make $<a>.Int * $<b>.Int } }
    token a   { \d+ }
    token b   { \d+ }
}

say Product.parse('4*5').made;

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

Output

20

Comments

  1. The two numbers are captured as <a> and <b>, each converted with .Int.

  2. The inline block combines the sub-matches — multiplying them — and stores the result on the match, which made then returns.

Course navigation

Multiply a pair   |   Reverse a word