Raku by Example: Multi Dispatch

Raku usually decides which subroutine to call based on the name of the sub and the content of its signature. In other words, Raku examines the content of the arguments passed to a sub and decides which candidate to call. In short, all the subroutines share the same name but differ in their signatures (type and number of the parameters). This behavior is known as multiple dispatch and Raku supports it by using the multi keyword.

multi congratulate('birthday', Str $person) {
    say "Happy birthday, $person!";
}

multi congratulate('birthday', Str :$person) {
    say "Happy birthday, $person!";
}

multi congratulate('birthday', Str $person, Int $age) {
    my $ord-ind = 'th';
    given $age {
        when 10 < $age < 14 { succeed         } 
        when $age % 10 == 1 { $ord-ind = 'st' }
        when $age % 10 == 2 { $ord-ind = 'nd' }
        when $age % 10 == 3 { $ord-ind = 'rd' }
    }
    say "Happy $age"~"$ord-ind birthday, $person!";
}

multi congratulate('birthday', Str :$person, Int :$age) {
    my $ord-ind = 'th';
    given $age {
        when 10 < $age < 14 { succeed         } 
        when $age % 10 == 1 { $ord-ind = 'st' }
        when $age % 10 == 2 { $ord-ind = 'nd' }
        when $age % 10 == 3 { $ord-ind = 'rd' }
    }
    say "Happy $age"~"$ord-ind birthday, $person!";
}

multi congratulate('graduation', Str $person) {
    say "Congratulations for graduating, $person!";
}

multi congratulate('promotion', Str $person) {
    say "Congratulations for your promotion, $person!";
}

congratulate('birthday', 'Nel');
congratulate('birthday', 'Jos', 21);
congratulate('birthday', person => 'Charlie');
congratulate('birthday', person => 'Dia', age => 22);
congratulate('graduation', 'Richard');
congratulate('promotion', 'Dave');
Happy birthday, Nel!
Happy 12th birthday, Jos!
Happy birthday, Charlie!
Happy 22nd birthday, Dia!
Congratulations for graduating, Richard!
Congratulations for your promotion, Dave!
Back to main