Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an infix version for routine invocation in perl 6?

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?

like image 292
jjmerelo Avatar asked Apr 02 '18 15:04

jjmerelo


2 Answers

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)
like image 107
Brad Gilbert Avatar answered Oct 13 '22 02:10

Brad Gilbert


If you have defined values, you can use the infix operator andthen.

    say (^10 »andthen» (* * 2, * / 2).roll(4))
like image 4
wamba Avatar answered Oct 13 '22 03:10

wamba