加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl6 – Perl 6在循环遍历列表时显示索引

发布时间:2020-12-15 23:22:52 所属栏目:大数据 来源:网络整理
导读:循环遍历列表(或数组)时,有没有办法知道循环中当前元素的索引? 当然,问题可以通过索引循环来解决: my @aa = 8 .. 12;say "$_t@aa[$_]" for 0 ..^ @aa.elems; 但也许类似下面的内容是可能的(我用.CURRENT_INDEX标记我正在寻找的方法)? my @aa = 8 .. 12;s
循环遍历列表(或数组)时,有没有办法知道循环中当前元素的索引?

当然,问题可以通过索引循环来解决:

my @aa = 8 .. 12;
say "$_t@aa[$_]" for 0 ..^ @aa.elems;

但也许类似下面的内容是可能的(我用.CURRENT_INDEX标记我正在寻找的方法)?

my @aa = 8 .. 12;
say $_.CURRENT_INDEXt$_ for @aa;

解决方法

这就是真正发生的事情:

my @aa = 8 .. 12;

my iterator = @aa.iterator;

while ($_ := iterator.pull-one) !=:= IterationEnd {
  say $_
}

在这种情况下,迭代器中的值是执行Iterator角色的匿名类.

Iterator可能有也可能没有任何方法可以知道它产生了多少值.例如,Iterator for .roll(*)不需要知道它到目前为止产生了多少值,所以它不需要.

Iterator可以实现返回其当前索引的方法.

my @aa = 8 .. 12;

my iterator = class :: does Iterator {
  has $.index = 0;     # declares it as public (creates a method)
  has @.values;

  method pull-one () {
    return IterationEnd unless @!values;

    ++$!index;         # this is not needed in most uses of an Iterator
    shift @!values;
  }
}.new( values => @aa );

say "{iterator.index}t$_" for Seq.new: iterator;
1   8
2   9
3   10
4   11
5   12

您也可以在更高级别的构造中执行此操作;

my @aa = 8 .. 12;

my $index = 0;
my $seq := gather for @aa { ++$index; take $_ };

say "$indext$_" for $seq;

要使$_. CURRENT-INDEX工作,需要包装结果.

class Iterator-Indexer does Iterator {
  has Iterator $.iterator is required;
  has $!index = 0;

  method pull-one () {
    my current-value = $!iterator.pull-one;

    # make sure it ends properly
    return IterationEnd if current-value =:= IterationEnd;

    # element wrapper class
    class :: {
      has $.CURRENT-INDEX;
      has $.value;

      # should have a lot more coercion methods to work properly
      method Str () { $!value }

    }.new( CURRENT-INDEX => $!index++,value => current-value )
  }
}

multi sub with-index ( Iterator iter ){
  Seq.new: Iterator-Indexer.new: iterator => iter;
}
multi sub with-index ( Iterable iter ){
  Seq.new: Iterator-Indexer.new: iterator => iter.iterator;
}


my @aa = 8 .. 12;
say "$_.CURRENT-INDEX()t$_" for with-index @aa.iterator;
# note that $_ is an instance of the anonymous wrapper class

再次使用更高级别的构造:

my @aa = 8 .. 12;

my sequence := @aa.kv.map: -> $index,$_ {
  # note that this doesn't close over the current value in $index
  $_ but role { method CURRENT-INDEX () { $index }}
}

say "$_.CURRENT-INDEX()t$_" for sequence;

我认为你应该只使用.pairs,如果你想要这样的东西. (或使用.kv,但基本上需要使用带有两个参数的for的块形式)

my @aa = 8 .. 12;
say "$_.key()t$_.value()" for @aa.pairs;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读