这是解决前一个问题的另一种方法
my @bitfields;
for ^3 -> $i {
@bitfields[$i] = Bool.pick xx 3;
}
my @total = [\Z+] @bitfields;
say @total;
Run Code Online (Sandbox Code Playgroud)
它应该将每一行压缩添加到下一行,并累积该值.但是,这会产生错误
The iterator of this Seq is already in use/consumed by another Seq
(you might solve this by adding .cache on usages of the Seq, or
by assigning the Seq into an array)
in block <unit> at vanishing-total.p6 line 8
Run Code Online (Sandbox Code Playgroud)
知道如何解决这个问题吗?
首先xx创建一个序列
say (Bool.pick xx 3).^name; # Seq
Run Code Online (Sandbox Code Playgroud)
所以你可能想把它变成一个数组(或列表).
for ^3 -> $i {
@bitfields[$i] = [Bool.pick xx 3];
}
Run Code Online (Sandbox Code Playgroud)
而且.pick xx 3,我会使用.roll(3).
for ^3 -> $i {
@bitfields[$i] = [Bool.roll(3)];
}
Run Code Online (Sandbox Code Playgroud)
zip(Z)元运算符也会创建序列.
say ( [1,2] Z [3,4] ).perl;
# ((1, 3), (2, 4)).Seq
say ( [1,2] Z+ [3,4] ).perl
# (4, 6).Seq
Run Code Online (Sandbox Code Playgroud)
所以[\Z+]甚至不会按照你想要的两种输入方式工作.
say [\Z+]( [1,2], [3,4] ).perl;
# (Seq.new-consumed(), Seq.new-consumed()).Seq
say [\Z+]( 1, 2 ).perl;
# (Seq.new-consumed(), Seq.new-consumed()).Seq
Run Code Online (Sandbox Code Playgroud)
如果您执行某些操作来缓存中间值,它确实有效.
say [\Z+]( [1,2], [3,4] ).map(*.cache).perl
# ((3,), (4, 6)).Seq
say [\Z+]( [1,2], [3,4] ).map(*.list).perl
# ((3,), (4, 6)).Seq
say [\Z+]( [1,2], [3,4] ).map(*.Array).perl
# ([3], [4, 6]).Seq
Run Code Online (Sandbox Code Playgroud)
您可能还想在前面添加一个列表,然后选择一个.skip.
my @bitfields = [
[Bool::True, Bool::True, Bool::False],
[Bool::False, Bool::False, Bool::True ],
[Bool::False, Bool::True, Bool::True ]
];
say [\Z+]( @bitfields ).map(*.List)
# ((2) (1 1 1) (1 2 2))
say [\Z+]( (0,0,0), |@bitfields ).map(*.List).skip
# ((1 1 0) (1 1 1) (1 2 2))
Run Code Online (Sandbox Code Playgroud)
如果你不需要中间结果[Z+]就可以正常工作.
say [Z+]( Bool.roll(3) xx 3 ) for ^5;
# (0 1 3)
# (1 2 1)
# (1 0 3)
# (0 1 2)
# (1 2 2)
Run Code Online (Sandbox Code Playgroud)