1

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);
}
Brian Dolan
  • 3,086
  • 2
  • 24
  • 35

1 Answers1

2

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).

Brad
  • 3,839
  • 7
  • 25
ben-albrecht
  • 1,785
  • 10
  • 23