Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Document {call,next}{same,with}
  • Loading branch information
moritz committed Feb 20, 2015
1 parent f442416 commit a7d5119
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions lib/Language/functions.pod
Expand Up @@ -428,4 +428,80 @@ say square 3; # 18
See L<type Routine|/type/Routine> for the documentation of built-in routine
traits.
=head1 Re-dispatching
There are cases in which a routine might want to call the next method
from a chain. This chain could be a list of parent classes in a class
hierarchy, or it could be less specific multi candidates from a multi
dispatch, or it could be the inner routine from a C<wrap>.
In all those cases, you can use C<callwith> to call the next routine in the
chain with arguments of your own choice.
For example
=begin code
multi a(Any $x) {
say "Any $x";
return 5;
}
multi a(Int $x) {
say "Int $x";
my $res = callwith($x + 1);
say "Back in Int with $res";
}
a 1;
=end code
produces this output:
=begin code
Int 1
Any 2
Back in Int with 5
=end code
Here C<a 1> calls the most specific C<Int> candidate first, and C<callwith>
re-dispatches to the less specific C<Any> candidate.
Very often, a re-dispatch passes the same argument along that the caller
received, so there is a special routine for that: C<callsame>.G
=begin code
multi a(Any $x) {
say "Any $x";
return 5;
}
multi a(Int $x) {
say "Int $x";
my $res = callsame;
say "Back in Int with $res";
}
a 1; # Int 1\n Any 1\n Bakc in Int with 5
=end code
Another common use case is to re-dispatch to the next routine in the chain,
and not do anything else aftwards. That's why we have C<nextwith> and
C<nextsame>, which call the next routine with arbitrary arguments
(C<nextwith>) or with the same argument as the caller received (C<nextsame>),
but never return to the caller. Or to phrase it differently, the C<nextsame>
and C<nextwith> variants replace the current callframe with the next
candidate.
=begin code
multi a(Any $x) {
say "Any $x";
return 5;
}
multi a(Int $x) {
say "Int $x";
nextsame;
say "back in a"; # never executed, because 'nextsame' doesn't return
}
a 1; # Int 1\n Any 1
=end code
=end pod

0 comments on commit a7d5119

Please sign in to comment.