我如何打破一个循环?
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没有它们。为什么?
它们有点迫不得已;最好使用许多较小的函数
发布如何与闭包交互。
他们是不需要的!
怎么解释呢?
我是Scala的新手,但是这样可以避免抛出异常和重复方法:
object awhile {
def apply(condition: () => Boolean, action: () => breakwhen): Unit = {
while (condition()) {
action() match {
case breakwhen(true) => return ;
case _ => { };
}
}
}
case class breakwhen(break:Boolean);
像这样使用它:
var i = 0
awhile(() => i < 20, () => {
i = i + 1
breakwhen(i == 5)
});
println(i)
如果你不想断:
awhile(() => i < 20, () => {
i = i + 1
breakwhen(false)
});
我是Scala的新手,但是这样可以避免抛出异常和重复方法:
object awhile {
def apply(condition: () => Boolean, action: () => breakwhen): Unit = {
while (condition()) {
action() match {
case breakwhen(true) => return ;
case _ => { };
}
}
}
case class breakwhen(break:Boolean);
像这样使用它:
var i = 0
awhile(() => i < 20, () => {
i = i + 1
breakwhen(i == 5)
});
println(i)
如果你不想断:
awhile(() => i < 20, () => {
i = i + 1
breakwhen(false)
});