Possible duplicate:Reduction for loop in Scala?
While running Scala For Impatient, I came up with the following exercise:
Write a Scala equivalent for the Java loop for (int i = 10; i> = 0; i--) System.out.println (i);
It didn't take me long to come up with the following solution:
for (i <- 1 to 10 reverse) { println(i) }
However, it made me think about how to reason about the cost of this. Does the inverse O (n) method go around the range, or does it decorate it with something that does fantastic index arithmetic? Are there other designs that can do this better?
You can always choose a step:
for (i <- 10 to 1 by -1) { println(i) }
. , Range ( O (1)):
final override def reverse: Range = if (length > 0) new Range.Inclusive(last, start, -step) else this