Course of Raku / Regexes and grammars / Grammars / The parse tree, make and made / Exercises / Reverse the words
Solution: Reverse the words
Here is a possible solution to the task.
Code
grammar Phrase {
token TOP { <word> [ ' ' <word> ]* { make $<word>».made.join(' ') } }
token word { \w+ { make $/.flip } }
}
say Phrase.parse('hello world').made;🦋 You can find the source code in the file reverse-the-words.raku.
Output
olleh dlrowComments
Each
wordtoken makes its own reversed text: its inline block runs whenever a word matches, andmake $/.flipstores the word —$/is the current match — spelled backwards.TOPmatches the words with<word> [ ' ' <word> ]*— one word, then any number of “space then word” — and combines them.$<word>is the list of every word match;».madepulls out the reversed text each one stored, and.join(' ')rebuilds the phrase with spaces.That “item, then item, then item…” shape is common enough to have a shorthand: the
%separator. Writing<word>+ % ' 'means “one or more<word>, separated by a space”, and matches exactly the same phrases as<word> [ ' ' <word> ]*— just more compactly.So
makeandmadework at two levels here: the small pieces make their values, and the whole is made from them. Reading.madeon the result givesolleh dlrow.