如何中斷循環?var largest=0for(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沒有它們。為什么?它們有點必要。更好地使用許多較小的函數發行如何與閉包進行交互。不需要它們!有什么解釋?
3 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
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
}
}
}

素胚勾勒不出你
TA貢獻1827條經驗 獲得超9個贊
打破for循環永遠不是一個好主意。如果您使用for循環,則意味著您知道要迭代多少次。使用帶有2個條件的while循環。
例如
var done = false
while (i <= length && !done) {
if (sum > 1000) {
done = true
}
}
添加回答
舉報
0/150
提交
取消