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;
say Bool.parse('unknown').defined;🦋 You can find the source code in the file proto-bool.raku.
Output
True
True
FalseComments
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”.'unknown'matches neither variant, so there is nothing for the proto token to dispatch to and the parse fails —False. The proto accepts exactly the alternatives you list, and nothing else.