Scala向下或减less循环?

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

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

你怎么做,所以从10到1? 我猜10 to 1给出一个空的迭代器(像平常的math范围)?

我做了一个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)) 
 scala> 10 to 1 by -1 res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) 

@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. 

在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 } 

用这种方法:

 for (i <- 10 downto 0) println(i) 

斯卡拉提供了许多方法,在循环中向下工作。

第一个解决scheme:用“到”和“由…”

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

第二种解决scheme:使用“至”和“反向”

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

第三个解决scheme:只有“到”

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