iteratorchapel

How do I perform a zip iterator in reverse? - Chapel


How can I perform a zip iterator in reverse order? I need to shift the elements of a sub array.

My code is as follows:

for (x,y) in zip({c..d by stride},{a..b by stride},){
    A1[x]=A1[y];
}

I need to perform this in reverse order(i.e b-->a & d-->c ) so as to avoid overwriting in case of an overlapping region . (a..b is always before c..d).


Solution

  • A few things to point out.

    First, in your code sample, it uses

    {c..d by stride}
    

    for example. The { } create a domain variable, but you just want to iterate over it. You can iterate over a range directly and that is both syntactically simpler and faster. I.e. don't write

    for i in {1..10} { ... } // unncessary domain
    

    instead, write this

    for i in 1..10 { ... } // good
    

    Now, to your question. Iterating over a range in reverse is done with a negative stride. Like this:

    for i in 1..5 by -1 {
      writeln(i);
    }
    

    outputs

    5
    4
    3
    2
    1
    

    Such reverse iteration can be zippered, like this:

    for (i,j) in zip( 1..5 by -1, 10..50 by -10 ) {
      writeln( (i,j) );
    }
    

    outputs

    (5, 50)
    (4, 40)
    (3, 30)
    (2, 20)
    (1, 10)