2017-08-28 54 views
1

我有一組對象var Players:[domain] Player和我想按相反順序迭代對象。像如何迭代Chapel中的域索引的對象

東西這工作

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 
} 

而且我想確保鞋子尺寸的更新。

== == UPDATE

一些額外的信息/規格兌現@ 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)); 
} 
+0

心靈提供更多細節在這裏,'poops',例如發生了什麼事與你的預期?編譯時失敗?執行時間失敗?意外的行爲? – bencray

+1

另外,如果相關,您能否提供'Players'的聲明並且它是元素類型?如果不相關,我們可以簡化這個例子嗎?Players是一個整數數組,我們更新每個元素的值? – bencray

回答

1

範圍操作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; 
} 
+0

作爲一個方面說明,我想知道是否應該在Chapel中工作。作爲功​​能請求,這可能值得探索。 – bencray