develooper Front page | perl.perl6.users | Postings from September 2021

Order of multi sub definitions can resolve dispatch ambiguity

Thread Next
From:
Joseph Brenner
Date:
September 24, 2021 06:32
Subject:
Order of multi sub definitions can resolve dispatch ambiguity
Message ID:
CAFfgvXX3UbEZX1cco-V8QHjP-BND+3rh2rt+hs54Kj8A7Y66Vw@mail.gmail.com
This code uses multi dispatch with constraints that are ambiguous
in a few cases, because there's some overlap in the lists of
monsters and heroes: 'mothera' and 'godzilla'.

    my @monsters = < godzilla  mothera     ghidora  gammera  golem
wormface >;
    my @heroes   = < beowulf   bluebeetle  bernie   mothera  godzilla
maynard_g_krebs >;

    subset Monster of Str where { $_ eq any( @monsters ) };
    subset Hero    of Str where { $_ eq any( @heroes ) };

    ## Monster is favored over Hero because of the order of definition
of these multi subs
    multi sub speak (Monster $m) {
        say "The monster, $m roars!";
    }
    multi sub speak (Hero $h) {
        say "The hero, $h shouts!";
    }

    speak('ghidora');  # The monster, ghidora roars!
    speak('beowulf');  # The hero, beowulf shouts!
    speak('mothera');  # The monster, mothera roars!

I would've expected that in the case of 'mothera', this would
error out unless an "is default" was added to one of the multi
subs.  Instead the ambiguity is resolved by the order of
definition: if you reverse the order of the "multi sub speak"s,
then mothera is treated as Hero not Monster.

This is not the behavior described in the documentation:

     https://docs.raku.org/language/glossary#index-entry-Multi-Dispatch
     Multi-dispatchยง

     The process of picking a candidate for calling of a set of
     methods or subs that come by the same name but with different
     arguments. The most narrow candidate wins. In case of an
     ambiguity, a routine with is default trait will be chosen if
     one exists, otherwise an exception is thrown.

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About