Say I want to apply an array of functions to an array of objects. Something like this:
my $a = sub ($) { $_ * 2 };
my $b = sub ($) { $_ / 2 };
my @funcs = ($a, $b);
my @ops = @funcs.roll(4);
I could do
say ^10 ».&» @ops;
but .&
is a postfix operator; same thing for >>., which could be used for a single function, however. Using
say ^10 Z. @ops;
with .
actually being the infix operator for calling a method, yields an error about mistaking it for the concatenation operator. I don't think I have any other option left. Any idea?
You could use the &infix:« o »
/ &infix:« ∘ »
operator, combined with a lambda/closure factory.
sub lambda-factory ( +in ) {
in.map: -> \_ { ->{_} }
}
my @funcs = (
* * 2,
* / 2
);
(@funcs X∘ lambda-factory ^10)».()
# (0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5)
(@funcs «∘» lambda-factory ^10)».()
# [0, 0.5, 4, 1.5, 8, 2.5, 12, 3.5, 16, 4.5]
( (|@funcs xx *) Z∘ lambda-factory ^10 )».()
# (0, 0.5, 4, 1.5, 8, 2.5, 12, 3.5, 16, 4.5)
If you have defined values, you can use the infix operator andthen
.
say (^10 »andthen» (* * 2, * / 2).roll(4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With