2016-01-19 3 views
7

1つの配列を唯一の要素とする配列の配列に配列をプッシュすると、このようなデータ構造が得られます。 ?Perl6:1つの要素を持つ配列の配列に配列をプッシュすると、正常に動作しないようです

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'は、リストの最後に一つのことを追加し、あなたがしたい場合は、' append'を使用一度に複数の要素を渡します。 –

答えて

8

これは、The single argument ruleに記載されている予想される動作です。

Perl 6は、「単一引数ルール」として知られている簡単な方法で解決する前に、その展開中に平坦化に関する多数のモデルを使用しています。

単一の引数のルールは、forループが行う反復回数を考慮することによって最もよく理解されます。繰り返すべきことは、常にforループの単一の引数、つまりルールの名前として扱われます。

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 

...リストコンストラクタ(インフィックス:<、>オペレータ)および配列作曲([...]接周辞)が規則に従う:

[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] 

驚きをもたらす可能性のある唯一のものは[[1]]ですが、非常に一般的な単一引数ルールに対する例外を保証するものではありません。

だから私は書くことができます。この作品にするために:

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

かも

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

もっと一般的な[Great List Refactor](https://perl6advent.wordpress.com/2015/12/14/day-15-2015-the-year-of-the-great-list-refactor/) – cuonglm

関連する問題