5 ms·
In Perl 6: @a.map({ $_ + 1 }).grep({ $_ % 3 != 0 }).map({ $_ * $_ }) Alternately, using the feed operator ==>: @a ==> map { $_ + 1 } ==> grep { $_ % 3 !=
by ekiru 16y ago
In Perl 6:
@a.map({ $_ + 1 }).grep({ $_ % 3 != 0 }).map({ $_ * $_ })
Alternately, using the feed operator ==>:
@a ==> map { $_ + 1 } ==> grep { $_ % 3 != 0 } ==> map { $_ * $_ }
And, if your code being readable to people who've never used Perl 6 and know nothing about it isn't a concern, you can use the much more concise Whatever star notation for closures:
@a ==> map * + 1 ==> grep * % 3 != 0 ==> map { $_ * $_ }
Using Whatever for the last one would neither work nor be readable(although you could do "* 2", but that's still suboptimal for readability), since the last "" in " * " would be interpreted as a second parameter.
If the preceding notations for anonymous functions have been too implicit for you, then you can use pointy blocks(or just plain anonymous function declarations).
@a ==> map -> $i { $i + 1 } ==> grep -> $i { $i % 3 != 0 } ==> map -> $i { $i * $i }
Or, you could use hyper operators instead of the maps:
((@a >>+>> 1).grep: {$_ % 3 != 0}) >>**>> 2
The hyper-operators extend the scalar operators "+" and "*" to lists. Since the ">>" point to their operands on the right side, that operand will be extended to be as long as the other side, allowing you to use a single scalar as the right-side element.
- Jach 16y agoI think this is a great example why Perl 6 highly intrigues me but at the same time scares the crap out of me. Thanks for sharing.