[] reduce with anonymous function in Perl 6

  • A+
Category:Languages

We can use reduce with a sub with two arguments, putting it in double brackets:

> sub mysum { $^a + $^b } > [[&mysum]] 1,3,5 9 

But what if we want to use an anonymous function instead?

Both following variants produce a compile error:

> [[&{ $^a + $^b }]] 1,3,5 > [[{ $^a + $^b }]] 1,3,5 


You are not allowed to have any spaces in that form of reduce.

> [[&({$^a+$^b})]] 1, 3, 5 9 

This is so that it is more obvious that it is a reduce, and not an array declaration.

> [ { $^a + $^b }, { $^a * $^b } ].pick.(3,5) 8 | 15 

The double [[…]] is just an extension of allowing any function to be used as an infix operator.

Note that you must use &(…) in this feature, when not talking about a named function &foo, or an already existing infix operator.

> 3 [&( { $^a + $^b } )] 5 8 

This is sort-of an extension of using […] for bracketing meta operators like Z and =

> @a [Z[[+]=]] 1..5 > @a Z[[+]=] 1..5 > @a Z[+=] 1..5 > @a Z+= 1..5 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: