首页 > 解决方案 > 馈送操作员管道的行为

问题描述

我正在使用以下代码对提要运算符进行试验:

my $limit=10000000;
my $list=(0,1...4);
sub task($_,$name) {
    say "Start $name on $*THREAD";
    loop ( my $i=0; $i < $limit; $i++ ){};
    say "End $name";
    Nil;
}

sub stage( &code, *@elements --> Seq) {
    map(&code,  @elements);
}

sub feeds() {
    my @results;
    $list
    ==> map ({ task($_, "stage 1"); say( now - ENTER now );$_+1})
    ==> map ({ task($_, "stage 2"); say( now - ENTER now );$_+1})
    ==> stage ({ task($_, "stage 3"); say( now - ENTER now );$_+1}) 
    ==> @results;

    say @results;
}

feeds();

运行时的输出是:

Start stage 1 on Thread<1>(Initial thread)
End stage 1
0.7286811
Start stage 2 on Thread<1>(Initial thread)
End stage 2
0.59053989
Start stage 1 on Thread<1>(Initial thread)
End stage 1
0.5955893
Start stage 2 on Thread<1>(Initial thread)
End stage 2
0.59050998
Start stage 1 on Thread<1>(Initial thread)
End stage 1
0.59472201
Start stage 2 on Thread<1>(Initial thread)
End stage 2
0.5968531
Start stage 1 on Thread<1>(Initial thread)
End stage 1
0.5917188
Start stage 2 on Thread<1>(Initial thread)
End stage 2
0.587358
Start stage 1 on Thread<1>(Initial thread)
End stage 1
0.58689858
Start stage 2 on Thread<1>(Initial thread)
End stage 2
0.59177099
Start stage 3 on Thread<1>(Initial thread)
End stage 3
3.8549498
Start stage 3 on Thread<1>(Initial thread)
End stage 3
3.8560015
Start stage 3 on Thread<1>(Initial thread)
End stage 3
3.77634317
Start stage 3 on Thread<1>(Initial thread)
End stage 3
3.6754558
Start stage 3 on Thread<1>(Initial thread)
End stage 3
3.672909
[3 4 5 6 7]

结果@result正确(in 中的输入$list增加了 3 次)

前两个阶段的输出拉动/交替,但第三阶段直到完成第 2 阶段的所有输入才执行

导致此行为的 map sub 的包装器是否存在问题?

此外,在包装器中进行评估所需的时间比直接调用 map 的时间要长得多。

任何帮助表示赞赏。

标签: raku

解决方案


slurpy 参数正在等待消耗传递给它的整个序列。考虑以下之间的区别:

perl6 -e 'sub foo($) { }; my $items := gather for 1..Inf { say $_ }; foo($items);'
perl6 -e 'sub foo(*@) { }; my $items := gather for 1..Inf { say $_ }; foo($items);'

第一个示例将完成,第二个示例将永远不会完成。因此,您可能希望将阶段功能更改为:

sub stage( &code, $elements --> Seq) {
    map(&code,  $elements);
}

推荐阅读