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
True

Comments

  1. The proto token bool has two named variants, true and false.

  2. 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”.

Course navigation

A boolean with proto   |   The parse tree, make and made