Scala向下或减少for循环? [英] Scala downwards or decreasing for loop?
本文介绍了Scala向下或减少for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Scala 中,您经常使用迭代器以递增顺序执行 for
循环,例如:
In Scala, you often use an iterator to do a for
loop in an increasing order like:
for(i <- 1 to 10){ code }
你会怎么做,让它从 10 变成 1?我猜 10 to 1
给出了一个空迭代器(就像通常的范围数学一样)?
How would you do it so it goes from 10 to 1? I guess 10 to 1
gives an empty iterator (like usual range mathematics)?
我制作了一个 Scala 脚本,它通过在迭代器上调用 reverse 来解决它,但在我看来这并不好,下面是要走的路吗?
I made a Scala script which solves it by calling reverse on the iterator, but it's not nice in my opinion, is the following the way to go?
def nBeers(n:Int) = n match {
case 0 => ("No more bottles of beer on the wall, no more bottles of beer." +
"
Go to the store and buy some more, " +
"99 bottles of beer on the wall.
")
case _ => (n + " bottles of beer on the wall, " + n +
" bottles of beer.
" +
"Take one down and pass it around, " +
(if((n-1)==0)
"no more"
else
(n-1)) +
" bottles of beer on the wall.
")
}
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)
这篇关于Scala向下或减少for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文