What are callwith and samewith supposed to do?

放肆的年华 提交于 2019-12-07 05:42:00

问题


What are callwith and samewith supposed to do? I thought callwith was supposed to run a subroutine of the same name of the current subroutine, but using the arguments I pass to it.

From the docs:

callwith calls the next matching candidate with arguments provided by users and returns that candidate's return value.

To me it sounds like inside the two-arity MAIN subroutine (i.e. MAIN($a,$b)) that callwith($x) would call MAIN($x).

But it doesn't:

multi MAIN ($a, $b) {
    my $result = callwith("$a$b");
    say "Got $result from MAIN(\$a)";
}

multi MAIN ($x)    {
    say "Hello $x";
    return True;
}
$ perl6 callwith.p6 foo bar
Use of uninitialized value $result of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to something meaningful.
  in sub MAIN at callwith.p6 line 3
Got  from MAIN($a)

Then this definition of samewith makes it sound like calling samewith($x) from inside of the two-arity MAIN (i.g. MAIN($a, $b)) would try to call the two-arity MAIN again ("current candidate", right?).

samewith calls current candidate again with arguments provided by users and returns return value of the new instance of current candidate.

But it actually calls the one-arity MAIN:

multi MAIN ($a, $b) {
    my $result = samewith("$a$b");
    say "Got $result from MAIN(\$a)";
}

multi MAIN ($x) {
    say "Hello $x";
    return True;
}
$ perl6 samewith.p6 foo bar
Hello foobar
Got True from MAIN($a)

So am I seeing correct behavior by callwith and samewith? If so, what am I misunderstanding? I'll gladly update the documentation once I understand this issue better.

I'm using Rakudo-Star-2018.01 on CentOS 7.4.1708.


回答1:


The behavior you are seeing is correct.

From But here's my dispatch, so callwith Maybe by Zoffix:

samewith — make the same call from scratch, following a new dispatch chain, with these new arguments, and come back

Zoffix also mentioned that if using one of the next____ or call_____ functions (e.g. nextwith or callwith), any previously rejected candidates will not be reconsidered.

So, it sounds like arity is already fixed before using callwith. samewith gets around this because it "redispatches" "from scratch" (Thanks Brad Gilbert for your comments, and Zoffix for your blog).

If you need to change arity, use samewith or just use the subroutine name again (MAIN in this case).



来源:https://stackoverflow.com/questions/49698773/what-are-callwith-and-samewith-supposed-to-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!