How Does One Make Scala Control Abstraction in Repeat Until?

后端 未结 4 958
挽巷
挽巷 2021-02-08 12:04

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?



        
4条回答
  •  灰色年华
    2021-02-08 12:14

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

提交回复
热议问题