Scala では、次のようにイテレータを使用してfor
増加順にループを実行することがよくあります。
for(i <- 1 to 10){ code }
10 から 1 になるようにするにはどうすればよいでしょうか?10 to 1
通常の範囲計算のように、空の反復子を返すのでしょうか?
イテレータでreverseを呼び出すことでこの問題を解決する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))
ベストアンサー1
scala> 10 to 1 by -1
res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)