在Scala中,您經常使用的迭代器做for
迴路中增加的順序,如:斯卡拉向下或減少循環?
for(i <- 1 to 10){ code }
你怎麼就這麼從10變爲1辦呢?我猜10 to 1
給出了一個空的迭代器(就像平常的數學範圍一樣)?
我做了一個Scala腳本,它通過調用迭代器上的反向來解決它,但在我看來這不是很好,下面的路要走嗎?
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))
@Felix:不客氣。我也應該指出,直到你可以用'to'來代替右邊的終點。左手端點始終包含在內。 – 2010-04-13 14:26:47
我已經知道until,until也是Integers上的一個函數,但是,「by」必須是範圍/迭代器上的函數,無論從「to」和「until」函數返回什麼。無論如何,謝謝:) – Felix 2010-04-15 12:59:58
蘭德爾的回答是最好的,但我認爲'Range.inclusive(10,1,-1)'值得一提。 – 2013-07-15 01:35:39