Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <strong>performance</strong> is no.</p> <p>The long answer to your more general question (having an <em>advantage</em>) is a little more contrived. Note that, by using <code>while</code>, you are in fact:</p> <ol> <li>creating a new variable that holds a counter.</li> <li>mutating that variable.</li> </ol> <p>Off-by-one errors and the perils of mutability will ensure that, on the long run, you'll introduce bugs with a <code>while</code> pattern. In fact, your <code>times</code> function could easily be implemented as:</p> <pre><code>def times(f: =&gt; Unit) = (1 to pip) foreach f </code></pre> <p>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 <code>while</code> construction would start to be even more difficult to read. Please attempt to implement the following using nothing but <code>whiles</code>:</p> <pre><code>def replicate(l: List[Int])(times: Int) = l.flatMap(x =&gt; List.fill(times)(x)) </code></pre> <p>Then proceed to define a tail-recursive function that does the same.</p> <hr> <p><strong>UPDATE:</strong> </p> <p>I hear you saying: "hey! that's cheating! <code>foreach</code> is neither a <code>while</code> nor a <code>tail-rec</code> call". Oh really? Take a look into Scala's definition of <code>foreach</code> for <code>Lists</code>:</p> <pre><code> def foreach[B](f: A =&gt; B) { var these = this while (!these.isEmpty) { f(these.head) these = these.tail } } </code></pre> <p>If you want to learn more about recursion in Scala, take a look at <a href="http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html" rel="nofollow noreferrer">this blog post</a>. Once you are into functional programming, go crazy and read Rúnar's <a href="http://apocalisp.wordpress.com/2011/10/26/tail-call-elimination-in-scala-monads/" rel="nofollow noreferrer">blog post</a>. Even more info <a href="http://dynamicsofprogramming.blogspot.co.uk/2013/01/loop-performance-and-local-variables-in.html" rel="nofollow noreferrer">here</a> and <a href="http://ochafik.com/blog/?p=806" rel="nofollow noreferrer">here</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload