在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))
until
,您还可以使用代替to
将右端点从范围中排除。始终包含左侧端点。