您的代码示例有一个错误,因为 'hi' 是一个整数(存储数组的大小)。例如,您的意思可能是“forall i in 1..hi”。无论哪种方式,这里都有一个代码清单,其中包含一些用于此类迭代的常见模式。
// Declare a 1-D array storing 10, 20, 30
// Such array literals start at index 1
var elements = [10,20,30];
// Note: elements.domain is the index set of the array;
// in this case {1..3}.
writeln("loop 1");
// iterate over range, accessing elements
for i in 1..elements.size {
writeln("Index: ", i, " Element: ", elements[i]);
}
writeln("loop 2");
// as above, but in parallel (output order will differ run to run)
forall i in 1..elements.size {
writeln("Index: ", i, " Element: ", elements[i]);
}
writeln("loop 3");
// zippered iteration to iterate over array, indexes at once
for (element,i) in zip(elements,elements.domain) {
writeln("Index: ", i, " Element: ", element);
}
writeln("loop 4");
// as above, but in parallel (output order will differ run to run)
forall (element,i) in zip(elements,elements.domain) {
writeln("Index: ", i, " Element: ", element);
}
也可以看看
http://chapel.cray.com/docs/latest/users-guide/base/forloops.html
http://chapel.cray.com/docs/latest/users-guide/base/zip.html
http://chapel.cray.com/docs/latest/primers/ranges.html