Search code examples
scalaperformancescala-2.9

counting down in scala for loop


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/


Solution

  • 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