Scala downwards or decreasing for loop?

前端 未结 7 967
死守一世寂寞
死守一世寂寞 2020-12-13 01:56

In Scala, you often use an iterator to do a for loop in an increasing order like:

for(i <- 1 to 10){ code }

How would you d

相关标签:
7条回答
  • 2020-12-13 02:13

    You can use Range class:

    val r1 = new Range(10, 0, -1)
    for {
      i <- r1
    } println(i)
    
    0 讨论(0)
  • 2020-12-13 02:17
    for (i <- 10 to (0,-1))
    

    The loop will execute till the value == 0, decremented each time by -1.

    0 讨论(0)
  • 2020-12-13 02:20
    scala> 10 to 1 by -1
    res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    
    0 讨论(0)
  • 2020-12-13 02:20

    You can use : for (i <- 0 to 10 reverse) println(i)

    0 讨论(0)
  • 2020-12-13 02:25

    The answer from @Randall is good as gold, but for sake of completion I wanted to add a couple of variations:

    scala> for (i <- (1 to 10).reverse) {code} //Will count in reverse.
    
    scala> for (i <- 10 to(1,-1)) {code} //Same as with "by", just uglier.
    
    0 讨论(0)
  • 2020-12-13 02:36

    Having programmed in Pascal, I find this definition nice to use:

    implicit class RichInt(val value: Int) extends AnyVal {
      def downto (n: Int) = value to n by -1
      def downtil (n: Int) = value until n by -1
    }
    

    Used this way:

    for (i <- 10 downto 0) println(i)
    
    0 讨论(0)
提交回复
热议问题