Scala向下或减少循环? [英] Scala downwards or decreasing for loop?
本文介绍了Scala向下或减少循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
循环,例如:
<$ p对于(i <-1至10){code}
你会怎么做,所以从10到1?我想> 10到1
给出一个空的迭代器(就像平常的数学范围一样)?
我做了一个Scala脚本通过在迭代器上调用reverse可以解决这个问题,但是我认为这不是很好,是下面的方法吗?
def nBeers(n:Int)= n匹配{
情况0 => (没有更多瓶啤酒在墙上,没有更多的啤酒瓶。+
\去商店买更多,+
在墙上的99瓶啤酒。 \\\
)
案例_ => (n +在墙上的啤酒瓶,+ n +
啤酒瓶。+
取下一个并传给它+
((n-1)== 0)
no more
else
(n-1))+
墙上的啤酒瓶 )
$ b $(b < - (0到99)。
println(nBeers(b))
解决方案
scala> 10到1 by -1
res1:scala.collection.immutable.Range =范围(10,9,8,7,6,5,4,3,2,1)
In Scala, you often use an iterator to do a for
loop in an increasing order like:
for(i <- 1 to 10){ code }
How would you do it so it goes from 10 to 1? I guess 10 to 1
gives an empty iterator (like usual range mathematics)?
I made a Scala script which solves it by calling reverse on the iterator, but it's not nice in my opinion, is the following the way to go?
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> 10 to 1 by -1
res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
这篇关于Scala向下或减少循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文