4

Possible Duplicate:
Decreasing for loop in Scala?

While working through [Scala For The Impatient][1], I came upon the following exercise:

Write a Scala equivalent for the Java loop
       for (int i = 10; i >= 0; i--) System.out.println(i);

It did not take me long to come up with the following solution:

   for (i <- 1 to 10 reverse) {
       println(i)
   }

However, this made me wonder about how to reason about the cost of doing this. Does the reverse method do an O(n) traversal of the Range, or does it decorate it with something that does fancy index arithmetic? Are there other constructs that can do this better? [1]: http://horstmann.com/scala/

0

1 Answer 1

18

You always can choose step:

for (i <- 10 to 1 by -1) {
       println(i)
}

According to your question about complexity. You can use reversed too, cause under cover new Range will be created with reversed order (it's O(1) operation):

final override def reverse: Range =
    if (length > 0) new Range.Inclusive(last, start, -step)
    else this

That is pretty constant

Sign up to request clarification or add additional context in comments.

4 Comments

Should be "10 to 1 by -1". I personaly like "(10 to 1 by -1) foreach println" better
I tried this using by -1 instead of reverse and it produces no output, which I take to mean that it iterates zero times. I wonder what I could be doing wrong.
@pohl as Gerd noted we need to swap 1 and 10, to get 10 to 1 by -1
Yikes. Yup, that was it. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.