我如何打破一个循环?

var largest=0
for(i<-999 to 1 by -1) {
    for (j<-i to 1 by -1) {
        val product=i*j
        if (largest>product)
            // I want to break out here
        else
           if(product.toString.equals(product.toString.reverse))
              largest=largest max product
    }
}

如何将嵌套for循环转换为尾递归?

来自FOSDEM 2009 Scala Talk http://www.slideshare.net/Odersky/fosdem-2009-1013261 第22页:

中断并继续 Scala没有它们。为什么? 它们有点迫不得已;最好使用许多较小的函数 发布如何与闭包交互。 他们是不需要的!

怎么解释呢?


当前回答

// import following package
import scala.util.control._

// create a Breaks object as follows
val loop = new Breaks;

// Keep the loop inside breakable as follows
loop.breakable{
// Loop will go here
for(...){
   ....
   // Break will go here
   loop.break;
   }
}

使用Break模块 http://www.tutorialspoint.com/scala/scala_break_statement.htm

其他回答

这在Scala 2.8中有所改变,它有一种使用断点的机制。您现在可以执行以下操作:

import scala.util.control.Breaks._
var largest = 0
// pass a function to the breakable method
breakable { 
    for (i<-999 to 1  by -1; j <- i to 1 by -1) {
        val product = i * j
        if (largest > product) {
            break  // BREAK!!
        }
        else if (product.toString.equals(product.toString.reverse)) {
            largest = largest max product
        }
    }
}

这是一个尾部递归的版本。不可否认,与for推导式相比,它有点晦涩,但我认为它是功能性的:)

def run(start:Int) = {
  @tailrec
  def tr(i:Int, largest:Int):Int = tr1(i, i, largest) match {
    case x if i > 1 => tr(i-1, x)
    case _ => largest
  }

  @tailrec
  def tr1(i:Int,j:Int, largest:Int):Int = i*j match {
    case x if x < largest || j < 2 => largest
    case x if x.toString.equals(x.toString.reverse) => tr1(i, j-1, x)
    case _ => tr1(i, j-1, largest)
  }

  tr(start, 0)
}

如您所见,tr函数是外部for推导式的对应函数,tr1是内部for推导式的对应函数。如果你知道如何优化我的版本,欢迎你。

在scala中我们能做的就是

scala> import util.control.Breaks._

scala> object TestBreak {
       def main(args : Array[String]) {
         breakable {
           for (i <- 1 to 10) {
             println(i)
             if (i == 5)
               break;
       } } } }

输出:

scala> TestBreak.main(Array())
1
2
3
4
5

由于Scala中还没有break,您可以尝试使用return语句来解决这个问题。因此,您需要将内部循环放入函数中,否则返回将跳过整个循环。

然而,Scala 2.8包含了一种打破的方法

http://www.scala-lang.org/api/rc/scala/util/control/Breaks.html

跳出for循环从来都不是一个好主意。如果你正在使用for循环,这意味着你知道你想要迭代多少次。使用带有两个条件的while循环。

例如

var done = false
while (i <= length && !done) {
  if (sum > 1000) {
     done = true
  }
}