How Does One Make Scala Control Abstraction in Repeat Until?

后端 未结 4 955
挽巷
挽巷 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:18

    You don't need the 2nd pair of braces, the usage should be:

    repeatLoop (x) until (cond) //or...
    repeatLoop {x} until {cond}
    

    And not:

    repeatLoop {x} { until(cond) } //EXTRA PAIR OF BRACES
    

    The error means that Scala thinks you are trying to call a method with a signature something like:

    def repeatLoop(x: => Unit)(something: X) //2 parameter lists
    

    And can find no such method. It is saying "repeatLoop(body)" does not take parameters. A full code listing for the solution probably looks something a bit more like:

    object Control0 {
      def repeatLoop(body: => Unit) = new Until(body)
    
      class Until(body: => Unit) {
        def until(cond: => Boolean) {
          body;
          val value: Boolean = cond;
    
          if (value) repeatLoop(body).until(cond)
        }
      }
    
    
      def main(args: Array[String]) {
        var y: Int = 1
        println("testing ... repeatUntil() control structure")
        repeatLoop {
          println("found y=" + y)
          y += 1
        }.until(y < 10)
      }
    }
    

    There are two useful observations to make here:

    1. The solution is not tail-recursive and will result in a StackOverflowError for long iterations (try while (y < 10000))
    2. The until seems the wrong way round to me (it would be more natural to stop when the condition becomes true, not carry on while it is true).

提交回复
热议问题