sub callwith

Documentation for sub callwith assembled from the following types:

language documentation Functions

From Functions

(Functions) sub callwith

callwith calls the next candidate matching the original signature, that is, the next function that could possibly be used with the arguments provided by users and returns that candidate's return value.

proto a(|) {*}
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;        # OUTPUT: «Int 1␤Any 2␤Back in Int with 5␤» 

Here, a 1 calls the most specific Int candidate first, and callwith re-dispatches to the less specific Any candidate. Note that although our parameter $x + 1 is an Int, still we call the next candidate in the chain.

In this case, for example:

proto how-many(|) {*}
multi how-manyAssociative $a ) {
    say "Associative $a ";
    my $calling = callwith1 => $a );
    return $calling;
multi how-manyPair $a ) {
    say "Pair $a ";
    return "There is $a "
multi how-manyHash $a ) {
    say "Hash $a";
    return "Hashing $a";
my $little-piggie = little => 'piggie';
say $little-piggie.^name;        # OUTPUT: «Pair␤» 
say &how-many.cando( \( $little-piggie ));
# OUTPUT: «(sub how-many (Pair $a) { #`(Sub|68970512) ... } sub how-many (Associative $a) { #`(Sub|68970664) ... })␤» 
say how-many$little-piggie  ); # OUTPUT: «Pair little     piggie␤There is little piggie␤» 

the only candidates that take the Pair argument supplied by the user are the two functions defined first. Although a Pair can be easily coerced to a Hash, here is how signatures match:

say :Pair ) ~~ :Associative ); # OUTPUT: «True␤» 
say :Pair ) ~~ :Hash );        # OUTPUT: «False␤» 

The arguments provided by us are a Pair. It does not match a Hash, so the corresponding function is thus not included in the list of candidates, as can be seen by the output of &how-many.cando( \( $little-piggie ));.