在Scala中,您经常使用迭代器以for递增的顺序执行循环,如:
for(i <- 1 to 10){ code }
Run Code Online (Sandbox Code Playgroud)
你会怎么做,所以它从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 …Run Code Online (Sandbox Code Playgroud) 可能重复:
减少Scala中的循环?
在通过Scala For The Impatient进行工作时,我接受了以下练习:
Write a Scala equivalent for the Java loop
for (int i = 10; i >= 0; i--) System.out.println(i);
我花了很长时间才提出以下解决方案:
for (i <- 1 to 10 reverse) {
println(i)
}
Run Code Online (Sandbox Code Playgroud)
然而,这让我想知道如何推断这样做的成本.反向方法是否进行了范围的O(n)遍历,还是用一些花式索引算法来装饰它?还有其他结构可以做得更好吗?
我是Scala的新手,从命令性的背景来看这个,但我想用功能术语来理解它.我对以下代码片段的行为非常困惑.
val res = for {
i <- 1 to 2
j <- 1 to 2
} yield (i, j)
println(s"res is $res")
Run Code Online (Sandbox Code Playgroud)
此代码将打印res是Vector((1,1),(1,2),(2,1),(2,2))如预期的那样.但是稍微修改上面的内容
val res = for {
i <- 1 to 2
j <- i to 0
} yield (i, j)
println(s"res is $res")
Run Code Online (Sandbox Code Playgroud)
打印res是Vector()
为什么第二个版本的循环不会产生Vector((1,1),(1,0),(2,2),(2,1),(2,0))?
这种行为对我使用Scala中的索引遍历2D矩阵的能力产生了重大影响.一般来说,如何在一个惯用的方式中循环遍历矩阵的上三角部分,同时跟踪行和列索引?
scala ×3
for-loop ×2
iterator ×1
loops ×1
nested-loops ×1
performance ×1
reasoning ×1
scala-2.9 ×1