Course of Raku / Essentials / Associative data types / Exercises / Replace with antonyms

Solution: Replace with antonyms

To solve the task, the contents of the file dictionary.raku is copied to the solution file replace-with-antonyms.raku. After that, a loop over the input arguments is trying to find the word in the dictionary, and if it can, it takes the antonym. If there is no such word in the dictionary, the original word is used.

Code

The solution is presented below. The dictionary is shown only partially here.

my %dictionary =
    'above' => 'below',
    'absent' => 'present',
    'achieve' => 'fail',
    # . . .
    'wrong' => 'right',
    'young' => 'old'    
;

for @*ARGS -> $word {
    say %dictionary{$word} // $word;
}

🦋 Find the program in the file replace-with-antonyms.raku.

Output

$ raku exercises/associatives/replace-with-antonyms.raku early morning
late
evening

$ raku exercises/associatives/replace-with-antonyms.raku big soft drive
small
hard
drive

Comments

  1. The // operator is the defined-or operator, which returns the first defined operand.
  2. In the hash, all the keys are words (i.e., they look like identifiers), so you don’t need to quote them in the hash. It is thus possible to create a hash, as shown below:
my %dictionary =
    above => 'below',
    absent => 'present',
    achieve => 'fail',
    # . . .
    wrong => 'right',
    young => 'old'    
;

Next exercise

💪 Purchase table

Course navigation

Positional data types / Subscripting ranges   |   Creating and calling functions