Is there any advantage to avoiding while loops in Scala?

前端 未结 3 1833
灰色年华
灰色年华 2021-02-01 06:45

Reading Scala docs written by the experts one can get the impression that tail recursion is better than a while loop, even when the latter is more concise and clearer. This is o

3条回答
  •  孤城傲影
    2021-02-01 07:02

    I'm pretty sure that, due to the limitations of the JVM, not every potentially tail-recursive function will be optimised away by the Scala compiler as so, so the short (and sometimes wrong) answer to your question on performance is no.

    The long answer to your more general question (having an advantage) is a little more contrived. Note that, by using while, you are in fact:

    1. creating a new variable that holds a counter.
    2. mutating that variable.

    Off-by-one errors and the perils of mutability will ensure that, on the long run, you'll introduce bugs with a while pattern. In fact, your times function could easily be implemented as:

    def times(f: => Unit) = (1 to pip) foreach f
    

    Which not only is simpler and smaller, but also avoids any creation of transient variables and mutability. In fact, if the type of the function you are calling would be something to which the results matter, then the while construction would start to be even more difficult to read. Please attempt to implement the following using nothing but whiles:

    def replicate(l: List[Int])(times: Int) = l.flatMap(x => List.fill(times)(x))
    

    Then proceed to define a tail-recursive function that does the same.


    UPDATE:

    I hear you saying: "hey! that's cheating! foreach is neither a while nor a tail-rec call". Oh really? Take a look into Scala's definition of foreach for Lists:

      def foreach[B](f: A => B) {
        var these = this
        while (!these.isEmpty) {
          f(these.head)
          these = these.tail
        }
      }
    

    If you want to learn more about recursion in Scala, take a look at this blog post. Once you are into functional programming, go crazy and read Rúnar's blog post. Even more info here and here.

提交回复
热议问题