Brian Dolan
Brian Dolan

Reputation: 3136

Chapel iterators with conditionals

I am trying to write an iterator with a conditional in Chapel. This works

var x = [1,4,5,2,6,3];

iter dx(x) {
  for y in x do yield 2*y;
}

for y in dx(x) {
  writeln("y -> ", y);
}

returning

y -> 2
y -> 8
y -> 10
y -> 4
y -> 12
y -> 6

Suppose I want to only return the ones that are greater than 3. None of these will compile. What is the proper syntax?

var x = [1,4,5,2,6,3];

iter dx(x) {
  //for y in x do {if x > 3} yield 2*y;  // Barf
  //for y in x do {if x > 3 yield 2*y }; // Barf
  //for y in x do if x > 3 yield 2*y ;   // Barf
}

for y in dx(x) {
  writeln("y -> ", y);
}

Upvotes: 1

Views: 80

Answers (1)

ben-albrecht
ben-albrecht

Reputation: 1865

The error is that you are checking against the iterator argument x instead of the current element y in the conditional. Try:

iter dx(x) {
  for y in x {
    if y > 3 {
      yield 2*y; 
    }
  }
}

or in the more concise form:

iter dx(x) {
  for y in x do if y > 3 then yield 2*y; 
}

Note that when the body of an if statement is a single statement, you may use a then keyword to introduce the body rather than enclosing it in braces { }. Unlike C, the then keyword is required (due to syntactic ambiguities that would occur otherwise).

Upvotes: 2

Related Questions