如何使Scala重复控制直到抽象? [英] How Does One Make Scala Control Abstraction in Repeat Until?
问题描述
我是Peter Pilgrim。我看到Martin Odersky在Scala中创建了控件抽象。但是,我似乎还不能在IntelliJ IDEA 9中重复它。是IDE吗?
I am Peter Pilgrim. I watched Martin Odersky create a control abstraction in Scala. However I can not yet seem to repeat it inside IntelliJ IDEA 9. Is it the IDE?
package demo
class Control {
def repeatLoop ( body: => Unit ) = new Until( body )
class Until( body: => Unit ) {
def until( cond: => Boolean ) {
body;
val value: Boolean = cond;
println("value="+value)
if ( value ) repeatLoop(body).until(cond)
// if (cond) until(cond)
}
}
def doTest2(): Unit = {
var y: Int = 1
println("testing ... repeatUntil() control structure")
repeatLoop {
println("found y="+y)
y = y + 1
}
{ until ( y < 10 ) }
}
}
错误消息为:
信息:编译完成,出现1条错误和0条警告
信息:1条错误
信息:0条警告
C:\Users\Peter\IdeaProjects\HelloWord\src\demo\Control.scala
错误:Error:第(57)行错误:Control.this.repeatLoop ({
scala.this.Predef.println( found y =。+(y));
y = y。+(1)
})类型的Control.this.Until不会接受参数
repeatLoop {
Information:Compilation completed with 1 error and 0 warnings
Information:1 error
Information:0 warnings
C:\Users\Peter\IdeaProjects\HelloWord\src\demo\Control.scala
Error:Error:line (57)error: Control.this.repeatLoop({
scala.this.Predef.println("found y=".+(y));
y = y.+(1)
}) of type Control.this.Until does not take parameters
repeatLoop {
可以认为rried函数的主体可以返回一个表达式(y + 1的值),但是repeatUntil的声明主体参数明确指出可以忽略还是不忽略?
In the curried function the body can be thought to return an expression (the value of y+1) however the declaration body parameter of repeatUntil clearly says this can be ignored or not?
错误是什么意思?
推荐答案
这是没有 StackOverflowError
。
scala> class ConditionIsTrueException extends RuntimeException
defined class ConditionIsTrueException
scala> def repeat(body: => Unit) = new {
| def until(condition: => Boolean) = {
| try {
| while(true) {
| body
| if (condition) throw new ConditionIsTrueException
| }
| } catch {
| case e: ConditionIsTrueException =>
| }
|
| }
| }
repeat: (body: => Unit)java.lang.Object{def until(condition: => Boolean): Unit}
scala> var i = 0
i: Int = 0
scala> repeat { println(i); i += 1 } until(i == 3)
0
1
2
scala> repeat { i += 1 } until(i == 100000)
scala> repeat { i += 1 } until(i == 1000000)
scala> repeat { i += 1 } until(i == 10000000)
scala> repeat { i += 1 } until(i == 100000000)
scala>
根据Jesper和Rex Kerr,这是一个没有例外的解决方案。
According to Jesper and Rex Kerr here is a solution without the Exception.
def repeat(body: => Unit) = new {
def until(condition: => Boolean) = {
do {
body
} while (!condition)
}
}
这篇关于如何使Scala重复控制直到抽象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!