Perl6: Pressing an array into an array of single element arrays does not seem to work properly

Why do I get such a data structure when I push arrays to an array of arrays that has one array as its only element?

use v6; my @d = ( [ 1 .. 3 ] ); @d.push( [ 4 .. 6 ] ); @d.push( [ 7 .. 9 ] ); for @d -> $r { say "$r[]"; } # 1 # 2 # 3 # 4 5 6 # 7 8 9 say @d.perl; # [1, 2, 3, [4, 5, 6], [7, 8, 9]] 
+7
arrays perl6
source share
1 answer

This is the expected behavior described in the Single Rule of Argument .

Perl 6 went through a series of models related to flattening during its evolution, before relying on a simple one, known as the β€œsingle argument rule”.

The only rule of the argument is better understood, given the number of iterations that the for loop will perform. The thing to iterate is always considered as one argument of the for loop, therefore the name of the rule.

 for 1, 2, 3 { } # List of 3 things; 3 iterations for (1, 2, 3) { } # List of 3 things; 3 iterations for [1, 2, 3] { } # Array of 3 things (put in Scalars); 3 iterations for @a, @b { } # List of 2 things; 2 iterations for (@a,) { } # List of 1 thing; 1 iteration for (@a) { } # List of @a.elems things; @a.elems iterations for @a { } # List of @a.elems things; @a.elems iterations 

... the list constructor (operator infix: <,>) and the composer of the array (traversal [...]) follow the rule:

 [1, 2, 3] # Array of 3 elements [@a, @b] # Array of 2 elements [@a, 1..10] # Array of 2 elements [@a] # Array with the elements of @a copied into it [1..10] # Array with 10 elements [ $@a ] # Array with 1 element (@a) [@a,] # Array with 1 element (@a) [[1]] # Same as [1] [[1],] # Array with a single element that is [1] [$[1]] # Array with a single element that is [1] 

The only one that may cause surprise is [[1]], but it is considered rare enough that it does not guarantee an exception to the rule of a single common argument.

So, to make this work, I can write:

 my @d = ( [ 1 .. 3 ], ); @d.push( [ 4 .. 6 ] ); @d.push( [ 7 .. 9 ] ); 

and

 my @d = ( $[ 1 .. 3 ] ); @d.push( [ 4 .. 6 ] ); @d.push( [ 7 .. 9 ] ); 
+8
source share

All Articles