Scala向下或减少循环?

Fel*_*lix 106 iterator loops for-loop scala

在Scala中,您经常使用迭代器以for递增的顺序执行循环,如:

for(i <- 1 to 10){ code }
Run Code Online (Sandbox Code Playgroud)

你会怎么做,所以它从10变为1?我想10 to 1给出一个空的迭代器(就像通常的范围数学)?

我制作了一个Scala脚本,它通过在迭代器上调用reverse来解决它,但是在我看来它不是很好,下面的方法是什么?

def nBeers(n:Int) = n match {

    case 0 => ("No more bottles of beer on the wall, no more bottles of beer." +
               "\nGo to the store and buy some more, " +
               "99 bottles of beer on the wall.\n")

    case _ => (n + " bottles of beer on the wall, " + n +
               " bottles of beer.\n" +
               "Take one down and pass it around, " +
              (if((n-1)==0)
                   "no more"
               else
                   (n-1)) +
                   " bottles of beer on the wall.\n")
}

for(b <- (0 to 99).reverse)
    println(nBeers(b))
Run Code Online (Sandbox Code Playgroud)

Ran*_*ulz 220

scala> 10 to 1 by -1
res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Run Code Online (Sandbox Code Playgroud)

  • 兰德尔的答案是最好的,但我认为`Range.inclusive(10,1,-1)`值得一提. (5认同)
  • @Felix:不客气。我还应该指出,还可以使用 `until` 代替 `to` 来从范围中排除右侧的端点。始终包括左侧端点。 (2认同)

Chi*_*rlo 35

@Randall的答案很好,但为了完成,我想添加几个变体:

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.
Run Code Online (Sandbox Code Playgroud)

  • +1表示第一个,但第二个是邪恶的 - 比`by`更不易读,在任何情况下都不应该使用IMO (9认同)
  • 第二个是邪恶的,但在可用的东西上建立直觉 (4认同)

Dip*_*haw 10

Scala提供了许多在循环中向下工作的方法.

第一个解决方案:使用"to"和"by"

//It will print 10 to 0. Here by -1 means it will decremented by -1.     
for(i <- 10 to 0 by -1){
    println(i)
}
Run Code Online (Sandbox Code Playgroud)

第二个解决方案:使用"to"和"reverse"

for(i <- (0 to 10).reverse){
    println(i)
}
Run Code Online (Sandbox Code Playgroud)

第三种解决方案:仅使用"至"

//Here (0,-1) means the loop will execute till value 0 and decremented by -1.
for(i <- 10 to (0,-1)){
    println(i)
}
Run Code Online (Sandbox Code Playgroud)

  • 所有这些选项已经涵盖(多年前). (4认同)

LP_*_*LP_ 6

在Pascal中编程后,我觉得这个定义很好用:

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
}
Run Code Online (Sandbox Code Playgroud)

用这种方式:

for (i <- 10 downto 0) println(i)
Run Code Online (Sandbox Code Playgroud)