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)
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)
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)
在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)
| 归档时间: |
|
| 查看次数: |
43738 次 |
| 最近记录: |