Course of Raku / Addendum 🆕 / Working with data / Text and strings / Exercises / Word frequency
Solution: Word frequency
Here is a possible solution to the task.
Code
my $text = 'the cat sat on the mat the cat';
my %freq;
%freq{$_}++ for $text.words;
for %freq.sort({ -.value, .key }) -> $pair {
say "{$pair.key}: {$pair.value}";
}🦋 You can find the source code in the file word-frequency.raku.
Output
the: 3
cat: 2
mat: 1
on: 1
sat: 1Comments
$text.wordsyields the words;%freq{$_}++bumps a counter for each, creating the key on first sight.Sorting by
-.valueputs the most frequent first; adding.keyas a second sort field breaks ties alphabetically, so the order is fully deterministic.