Created
May 18, 2014 13:57
-
-
Save moritz/08274d7e01ef4ff2c244 to your computer and use it in GitHub Desktop.
Fill positional arguments by name (Perl 6)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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