Course of Raku / Regexes and grammars / Grammars / Grammars, classes, and inheritance / Exercises / A boolean with proto
Solution: A boolean with proto
Here is a possible solution to the task.
Code
grammar Bool {
token TOP { <bool> }
proto token bool {*}
token bool:sym<true> { 'true' }
token bool:sym<false> { 'false' }
}
say Bool.parse('true').defined;
say Bool.parse('false').defined;🦋 You can find the source code in the file proto-bool.raku.
Output
True
TrueComments
The proto token
boolhas two named variants,trueandfalse.Each parse selects the matching variant, so both
'true'and'false'succeed. A proto token is the grammar’s tidy way of saying “one of these named alternatives”.