Course of Raku / Regexes and grammars / Grammars / Grammars, classes, and inheritance / Exercises / Inherit a grammar

Solution: Inherit a grammar

Here is a possible solution to the task.

Code

grammar Animal {
    token TOP   { <sound> }
    token sound { 'meow' }
}

grammar Dog is Animal {
    token sound { 'woof' }
}

say Dog.parse('woof').defined;

🦋 You can find the source code in the file inherit-a-grammar.raku.

Output

True

Comments

  1. Dog is Animal inherits the TOP token unchanged.

  2. It provides its own sound, which is the one used when Dog parses, so 'woof' matches — just as an overridden method replaces the parent’s version on an object.

Course navigation

Inherit a grammar   |   A number with proto