Scala'da, aşağıdaki forgibi artan bir sırayla döngü yapmak için genellikle bir yineleyici kullanırsınız :
for(i <- 1 to 10){ code }
10'dan 1'e çıkması için nasıl yaparsınız? Sanırım 10 to 1boş bir yineleyici veriyor (normal aralık matematiği gibi)?
Yineleyicide ters çağırarak sorunu çözen bir Scala betiği yaptım ama bence bu hoş değil, aşağıdaki yol mu?
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))
untilyerine kullanabileceğinizi de belirtmeliydimto. Sol taraftaki uç nokta her zaman dahil edilir.