如何迭代 Chapel 中由域索引的对象

How to iterate over objects indexed by a domain in Chapel

我有一组对象 var Players: [domain] Player 并且我想以相反的顺序遍历这些对象。像

这个有效

for p in Players by {
   writeln(p.name);
   writeln("I was the %i st player added".format(p.pid)")  // pid corresponds to domain index.
   p.shoeSize = 1.5*p.shoeSize
}

但是!

// poops
for p in Players by -1 {
   writeln(p.name);
   writeln("I was the %i -to-last player added".format(p.pid)")  // pid corresponds to domain index.
   p.shoeSize = 1.5*p.shoeSize
}

我想确保鞋码更新。

== 更新 ==

一些额外的信息/规格来满足@bencray 的要求

class Player {
  var name: string,
      position: string,
      pid: int,
      shoeSize: int;
}

var playerDom = {1..0},
    players: [playerDom] Player;

writeln("I have %i players".format(playerDom.size));
// Now add some players
// Better way to increase as I go along?
playerDom = {1..playerDom.size+1};
players[playerDom.size] = new Player(name="Gretsky", position="Center", shoeSize=10, pid=playerDom.size);
writeln("I have %i players".format(playerDom.size));

playerDom = {1..playerDom.size+1};
players[playerDom.size] = new Player(name="Blake", position="Defenseman", shoeSize=12, pid=playerDom.size);
writeln("I have %i players".format(playerDom.size));

for p in players {
  writeln("Player %i has shoeSize %i".format(p.pid, p.shoeSize));
  p.shoeSize += 1;
}

for p in players {
  writeln("Player NOW %i has shoeSize %i".format(p.pid, p.shoeSize));
}

// poops during compilation
// domobj.chpl:31: error: the first argument of the 'by' operator is not a range
for p in players by -1 {
  writeln("Player NOW %i has shoeSize %i".format(p.pid, p.shoeSize));
}

范围操作 by 不能像您希望的那样对数组起作用。相反,我们只剩下稍微不那么优雅的迭代反向索引的形式,如下所示:

for i in players.domain by -1 {
  writeln("Player NOW %i has shoeSize %i".format(players[i].pid, players[i].shoeSize));
}

下面是你的更大的代码块和一些其他的清理:

var playerDom = {1..0},
    players: [playerDom] Player;

writeln("I have %i players".format(playerDom.size));
players.push_back(new Player(name="Gretsky", position="Center", shoeSize=10, pid=players.size+1));
writeln("I have %i players".format(playerDom.size));
players.push_back(new Player(name="Blake", position="Defenseman", shoeSize=12, pid=players.size+1));
writeln("I have %i players".format(playerDom.size));

for p in players {
  writeln("Player %i has shoeSize %i".format(p.pid, p.shoeSize));
  p.shoeSize += 1;
}

for p in players {
  writeln("Player NOW %i has shoeSize %i".format(p.pid, p.shoeSize));
}

for i in players.domain by -1 {
  ref p = players[i];
  writeln("Player NOW %i has shoeSize %i".format(p.pid, p.shoeSize));
}

class Player {
  var name: string,
      position: string,
      pid: int,
      shoeSize: int;
}