Course of Raku / Advanced / More about built-in types / Sets, bags, and mixes / Exercises / Count in a bag

Solution: Count in a bag

Here is a possible solution to the task.

Code

my $words = bag('the cat sat on the mat'.words);

say $words<the>;
say $words.total;

🦋 You can find the source code in the file bag-count.raku.

Output

2
6

Comments

  1. 'the cat sat on the mat'.words produces the six words, and bag counts each one. Subscripting with <the> returns how many times the was seen — twice.

  2. The total method sums all the counts, which equals the number of words put into the bag — 6.

Course navigation

Count in a bag   |   Sequences