Course of Raku / Essentials / Associative data types / Exercises / Seen before?

Solution: Seen before?

This task is a classic example of using a hash to keep track of items. Before a loop, a hash %seen is created. Inside the loop, the entered $word serves a key of the hash.


Here is the solution:

my %seen;
loop {
    my $word = prompt 'Word: ';
    if %seen{$word} {
        say %seen{$word} == 1 ?? 'Seen!' !! say "Seen %seen{$word} times!";

🦋 Find the program in the file seen-before.raku.


$ raku exercises/associatives/seen-before.raku
Word: I
Word: never
Word: saw
Word: a
Word: saw
Word: that
Word: saw
Seen 2 times!
Word: as
Word: that
Word: saw
Seen 3 times!
Word: sawed
Word: ^C


The construct %seen{$word}++ not only increments the value but also creates it if it did not exist yet. The process of creating is called autovivification. Notice that it does not happen when you only read the value as in the condition: if %seen{$word}.

Next exercise

💪 Country codes

Course navigation

Positional data types / Subscripting ranges   |   Creating and calling functions