insta catering
insta catering

Reputation: 160

Chapel Iteration

Working on currently and trying to iterate through an array hi of type: eltType called elements and it has elements in it.

I am trying to iterate through the whole array hi and print out each element so I'm doing:

var hi : int;
hi = elements.size;
forall i in hi
{
    writeln("Index: ", 0, " Element: ", elements[i]);
}

When I try that I get this error:

Cannot iterate over values of type int(64)

Not sure how to iterate through it or why this error is happening.
Any ideas or guides? I've been looking at the Chapel API.

Upvotes: 1

Views: 233

Answers (1)

mppf
mppf

Reputation: 1845

Your code sample has a bug, since 'hi' is an integer (storing the size of the array). You might have meant 'forall i in 1..hi' for example. Either way, here is a code listing with some common patterns for such iteration.

// 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);
}

See also

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

Upvotes: 4

Related Questions