10

当我们使用超出数组边界的索引对数组进行切片时,我们会得到未定义 (Any)

当我们将相同的切片索引作为惰性列表传递时,我们会得到数组/列表的现有值(仅此而已):

my @a = ^5;

say @a[^10];        # (0 1 2 3 4 (Any) (Any) (Any) (Any) (Any))
say @a[lazy ^10];   # (0 1 2 3 4)

很明显,切片索引的惰性会影响结果。

试图理解事物的本来面目,作为概念证明,我编写了切片机制的简单版本:

my @a = ^5;

my @s1 = ^10;
my @s2 = lazy ^10;

sub postcircumfix:<-[ ]-> (@container, @index) {
    my $iter = @index.iterator;

    gather {
        loop {
            my $item := $iter.pull-one;

            if $item =:= IterationEnd {
                last;
            }

            with @container[$item] {
                take @container[$item]
            } else {
                @index.is-lazy ?? { last } !! take @container[$item];
            }
        }
    }
}

say @a-[@s1]-;   # (0 1 2 3 4 (Any) (Any) (Any) (Any) (Any))
say @a-[@s2]-;   # (0 1 2 3 4)

但我想知道我的幼稚算法是否描述了事物在幕后计算的方式!

4

1 回答 1

7

可以在array_slice.pm6中找到如何在幕后完成事情的源代码。

具体来说,您可以在 L73 看到以下内容:

    if is-pos-lazy {
        # With lazy indices, we truncate at the first one that fails to exists.
        my \rest-seq = Seq.new(pos-iter).flatmap: -> Int() $i {
            nqp::unless(
              $eagerize($i),
              last,
              $i
            )
        };
        my \todo := nqp::create(List::Reifier);
        nqp::bindattr(todo, List::Reifier, '$!reified', eager-indices);
        nqp::bindattr(todo, List::Reifier, '$!current-iter', rest-seq.iterator);
        nqp::bindattr(todo, List::Reifier, '$!reification-target', eager-indices);
        nqp::bindattr(pos-list, List, '$!todo', todo);
    }
    else {
        pos-iter.push-all: target;
    }

因此,正如您所推测的,它确实在列表项不存在后停止。这无疑是因为许多惰性列表是无限的,并且迭代器不提供一种方法来知道它们是否是无限的(生成器可能是非确定性的)。

如果你真的想启用这样的东西,例如,你可以编写自己的切片器来处理可能不可用的元素的惰性列表,但你必须注意确保只有在你知道它们的情况下才会急切地评估它们'是有限的:

multi sub postcircumfix:<-[ ]-> (@a, @b) {
  lazy gather {
    take @a[$_] for @b;
  }
}

my @a = ^5;
my @b = lazy gather { 
  for ^10 -> $i { 
    # So we can track when elements are evaluated
    say "Generated \@b[$i]"; 
    take $i;
  } 
};

say "Are we lazy? ", @a-[@b]-;
say "Let's get eager: ", @a-[@b]-.eager;
say "Going beyond indices: ", @a-[@b]-[11]

这个的输出是

Are we lazy? (...)
Generated @b[0]
Generated @b[1]
Generated @b[2]
Generated @b[3]
Generated @b[4]
Generated @b[5]
Generated @b[6]
Generated @b[7]
Generated @b[8]
Generated @b[9]
Let's get eager: (0 1 2 3 4 (Any) (Any) (Any) (Any) (Any))
Going beyond indices: Nil
于 2020-09-29T15:45:23.537 回答