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

Re: Order of multi sub definitions can resolve dispatch ambiguity

Thread Previous | Thread Next
From:
Joseph Brenner
Date:
September 30, 2021 22:03
Subject:
Re: Order of multi sub definitions can resolve dispatch ambiguity
Message ID:
CAFfgvXU-xSnOuR-pfjQnA29s_yLpGtH+BrV4vkVKk0W_DMTLeA@mail.gmail.com
Like I was saying:

> If the two [multis] are defined in different modules I suspect you
> could get some strange behavior that would be hard to debug.
> It's not always immediately obvious in what order two things were
> defined.

Here's an example, scattered across four files, which
I've also pushed out to github:

  https://github.com/doomvox/raku-study/blob/main/md_exp/

The deal here is one script treats "godzilla" as a Hero,
the other as a Monster, and the only difference is the
order of two "use" lines:

 ---
md_exp/lib/Speak/Monster.rakumod:

    module Speak::Monster {
        my @monsters  = < godzilla  gammera   ghidora   golem    >;
        subset Monster of Str where { $_ eq any( @monsters ) };
        multi sub speak (Monster $name) is export {
            say "The monster, $name roars!";
        }
    }


 ---
md_exp/lib/Speak/Hero.rakumod:

    module Speak::Hero {
        my @heroes    = < godzilla  beowulf   ultraman  inframan >;
        subset Hero of Str where { $_ eq any( @heroes ) };
        multi sub speak (Hero $name) is export {
            say "The hero, $name shouts!";
        }
    }

 ---
md_exp/bin/multidispatch_overlapping_subsets_use_order_dependency-a.raku

    use lib $*PROGRAM.parent(2).add("lib");
    {
      say "a: Hero Monster trial run";
      use Speak::Hero;
      use Speak::Monster;
      speak('godzilla');    ## The hero, godzilla shouts!
    }


 ---
md_exp/bin/multidispatch_overlapping_subsets_use_order_dependency-b.raku

    use lib $*PROGRAM.parent(2).add("lib");
    {
      say "a: Monster Hero trial run";
      use Speak::Monster;
      use Speak::Hero;
      speak('godzilla');    ## The monster, godzilla roars!
    }
 ---

But the situation is even worse than this: the
order-of-definition doesn't depend on the order of the
use lines in the block of code in front of you:
in a large code base you might have use lines scattered
in different places, and the order-of-definition is the
order in which raku first sees the use lines.

Thread Previous | 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