如何在Scala中打破循环?

如何中断循环?


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没有它们。为什么?它们有点必要。更好地使用许多较小的函数发行如何与闭包进行交互。不需要它们!


有什么解释?


慕标5832272
浏览 548回答 3
3回答

宝慕林4294392

Scala 2.8中对此进行了更改,它具有使用中断的机制。您现在可以执行以下操作:import scala.util.control.Breaks._var largest = 0// pass a function to the breakable methodbreakable {&nbsp;&nbsp; &nbsp; for (i<-999 to 1&nbsp; by -1; j <- i to 1 by -1) {&nbsp; &nbsp; &nbsp; &nbsp; val product = i * j&nbsp; &nbsp; &nbsp; &nbsp; if (largest > product) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; // BREAK!!&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else if (product.toString.equals(product.toString.reverse)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; largest = largest max product&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

素胚勾勒不出你

打破for循环永远不是一个好主意。如果您使用for循环,则意味着您知道要迭代多少次。使用带有2个条件的while循环。例如var done = falsewhile (i <= length && !done) {&nbsp; if (sum > 1000) {&nbsp; &nbsp; &nbsp;done = true&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP