Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does One Make Scala Control Abstraction in Repeat Until?

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 ) }
  }

}

The error message reads:

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 {

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?

What does the error mean?

like image 521
peter_pilgrim Avatar asked Jun 14 '10 09:06

peter_pilgrim


1 Answers

Here is a solution without the 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> 

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)
  }   
}
like image 80
3 revs Avatar answered Sep 30 '22 07:09

3 revs