Skip to content

Instantly share code, notes, and snippets.

@moritz
Created May 18, 2014 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/08274d7e01ef4ff2c244 to your computer and use it in GitHub Desktop.
Save moritz/08274d7e01ef4ff2c244 to your computer and use it in GitHub Desktop.
Fill positional arguments by name (Perl 6)
use v6;
sub t ($x, $y, :$label = 'sum') {
say "$label: ", $x + $y;
}
sub namecall(&c, *@pos, *%named is rw) {
my %name-to-idx;
for &c.signature.params.kv -> $idx, $p {
next if $p.named;
my $name = $p.name.substr(1);
%name-to-idx{$name} = $idx;
}
my @seen;
my @args;
# map named to positional
for %named.pairs -> $p {
if %name-to-idx{$p.key}.defined {
my $v := $p.value;
%named{$p.key}:delete;
my $idx = %name-to-idx{$p.key};
@args[$idx] := $v;
@seen[$idx] = True;
}
}
# fills the gaps
for @seen.kv -> $idx, $there {
unless $there {
unless (@pos) {
die "Too few arguments supplied!";
}
@args[$idx] := @pos.shift;
}
}
@args.push: @pos;
# call!
c |@args, |%named;
}
namecall &t, 40, x => 2, label => 'bla';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment