【发布时间】:2011-02-06 17:35:24
【问题描述】:
在 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))
【问题讨论】:
标签: scala iterator loops for-loop