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 { \w+ }
}
grammar Dog is Animal {
token sound { 'woof' }
}
grammar Cat is Animal {
token sound { 'meow' }
}
say Dog.parse('woof').defined;
say Cat.parse('meow').defined;
say Dog.parse('meow').defined;🦋 You can find the source code in the file inherit-a-grammar.raku.
Output
True
True
FalseComments
Both
Dog is AnimalandCat is Animalinherit theTOPtoken from the base unchanged; each supplies only its ownsound.So one base grammar is extended two different ways.
Dogmatches onlywoofandCatonlymeow— which is whyDog.parse('meow')fails: a dog keeps its own overriddensound, exactly as overridden methods behave on objects.