Seq 已经在 use/consumed 中(嵌套 gather / take )

Seq is already in use/consumed (nested gather / take )

sub f()
{
    gather
    {
        take gather { take 3; take 4; take 5; }
        take gather { take 1; take 2; take 3; }
    }
}

say f.sort

对决
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 so.raku line 1

sub f()
{
    gather
    {
        take cache gather { take 3; take 4; take 5; }
        take cache gather { take 1; take 2; take 3; }
    }
}

say f.sort

按预期工作并生成 ((1, 2 ,3), (3, 4, 5))。很好(感谢 raiph)。现在

sub MAIN( *@n )
{
    @n = @n || ( 3, 4, 5, -1, 111, 27, 28, 29, 1, 2 );

    chunks( @n, { $^left < $^right } )
        .sort({ [*] |$_ })
        .tail
        .say;
}

sub chunks( Iterable $list, &condition )
{
    my $windows = $list.rotor( 2 => -1, :partial ).iterator;
    my $done    = False;

    gather until $done
    {
        my Mu $window := $windows.pull-one;

        last if $window =:= IterationEnd;

        take cache gather
        {
            my $condition-result;

            while $window := $window // $windows.pull-one
            {
                $done = True and last if $window =:= IterationEnd;

                take $window[0];

                $condition-result = &condition( |$window )
                    if $window.elems == 2;

                $window := Any;
                last unless $condition-result;
            }
        }
    }
}

这应该会产生 (27 28 29),但它不会。它产生 (111)。但是当我用 take eager gather 替换 take cache gather 时,它按预期工作。

我的 chunks 函数与上面的简单示例具有相同的结构,我认为但行为似乎有所不同。

问题似乎出在您的 take gather 构造中。它把(仍然打开的)Seqs 放在你的大外 Seq 里面。我 "fixed" 你的代码,用 take my @x = gather 代替 take gather,我想一切都如你所愿。

总重写

存在三种可能的情况。

在所有这些中,take eager gather 是解决方案而不是 take gather

这留下了最外面的 gather

您可以保持原样。这意味着如果您将 chunks 调用的结果绑定到一个变量,然后对其进行两次迭代操作,您将得到 Seq is already in use/consumed 错误。

或者你可以解决那个问题。您有两个选择,具体取决于您更喜欢 chunks 操作是急切的还是惰性的。如果你想让它急于求成,那就把外面的gather写成eager gather。想要偷懒就写成cache gather.