2016-01-19 9 views
7

Perché ottengo questo tipo di struttura dati, quando spingo array in un array di array che ha un array come unico elemento ?Perl6: il push di un array su un array di array con un elemento sembra non funzionare come previsto

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]] 
+1

'push' aggiunge una cosa alla fine della lista, utilizzare' append' se si desidera per passare più di un elemento alla volta. –

risposta

8

Questo è il comportamento previsto descritto nello The single argument rule.

Perl 6 ha attraversato un certo numero di modelli relativi all'appiattimento durante la sua evoluzione, prima di stabilirsi in una semplice nota come "regola del singolo argomento".

La regola del singolo argomento è meglio compresa considerando il numero di iterazioni che farà un ciclo for. La cosa da iterare è sempre trattata come un singolo argomento per il ciclo for, quindi il nome della regola.

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 

... il costruttore lista (l'infisso: <,> operatore) e il compositore array (il [...] circonfisso) seguire la regola:

[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 
[[email protected]]     # 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] 

L'unico di questi che può fornire una sorpresa è [[1]], ma è ritenuto sufficientemente raro da non garantire un'eccezione alla regola del singolo argomento molto generale.

Quindi, per fare questo lavoro posso scrivere:

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

o anche

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

Forse più generale, [Great List Refactor] (https://perl6advent.wordpress.com/2015/12/14/day-15-2015-the-year-of-the-great-list-refactor/) – cuonglm

Problemi correlati