在Scala中,您经常使用迭代器以递增的顺序执行for循环,如下所示:
for(i <- 1 to 10){ code }你怎么做才能从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))发布于 2014-05-14 05:54:37
在用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)https://stackoverflow.com/questions/2617513
复制相似问题