Course of Raku / Regexes and grammars / Grammars / Action classes / Exercises / One grammar, two actions
Solution: One grammar, two actions
Here is a possible solution to the task.
Code
grammar Pair {
token TOP { <a> ',' <b> }
token a { \d+ }
token b { \d+ }
}
class Sum { method TOP($/) { make $<a>.Int + $<b>.Int } }
class Diff { method TOP($/) { make $<a>.Int - $<b>.Int } }
say Pair.parse('10,20', actions => Sum.new).made;
say Pair.parse('10,20', actions => Diff.new).made;🦋 You can find the source code in the file adder-action.raku.
Output
30
-10Comments
The grammar only describes the shape
number,number; it knows nothing about what to compute.The two action classes attach different meanings to the same parse — one sums the numbers, the other subtracts them. Passing a different
actionsobject to.parseis all it takes to get a different result, without changing the grammar at all.