in reply to Re^2: how to avoid using index of array
in thread how to avoid using index of array
For some reason I was expecting that the syntax should look more like this:for( @male Z @female )->[$m,$f] { # .... }
Close. Two things got into your way. The first is syntactic: you need a space between for and (. The reason is that (nearly) everything of the form identifier(...) is parsed as a subroutine call. That way keywords don't conflict with function names, making it more robust to introduce new syntax.
The second one is a bit more interesting. In a signature, [$m, $f] stands for a single parameter, which is taken as a list, and unpacked into the two variables. But @list1 Z @list2 returns a list of lists which flattens the sublists when you iterate over it. To stop that flattening, you can write
for (@male Z @female).tree ->[$m,$f] { # .... }
which indeed works in current Rakudo.
Also, how would you push a stringified concatenation onto a new array?
Several ways:
my @array; for @male Z @female -> $m, $f { push @array, "$m $f; # or @array.push: "$m $f"; # or @array.push: $m ~ ' ' ~ $f } # or my @array = (@male Z @female).map("$^a $^b");
Since Z can also be used as a meta operator, you can also get zip and concatenation in one go, using Z~:
my @array = @male Z~ @female; # without joining space
To get the space between the two operands, you can use one of these tricks:
# with the list repetition operator: @array = @male Z~ ' ' xx @male Z~ @female; # with cross instead of zip: @array = @male X~ ' ' Z~ @female;
All of these solutions work with current Rakudo.
|
|---|