Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting down in scala for loop [duplicate]

Possible Duplicate:
Decreasing for loop in Scala?

While working through Scala For The Impatient, 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?

like image 851
pohl Avatar asked Dec 01 '22 22:12

pohl


1 Answers

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

like image 134
om-nom-nom Avatar answered Dec 18 '22 11:12

om-nom-nom