title: Restructuring a method to fix tail recursive call not in tail position
body: <p>Consider the following recursive power method multiplication:</p>
  
  <pre><code>import scala.annotation.tailrec
  @tailrec def mult(x: Double, n:Int) : Double = {
        n match {
      case 0 =&gt; 1
      case 1 =&gt; x
      case _ if ((n &amp; 0x01) != 0) =&gt;  x * mult(x*x, (n-1)/2)
      case _ =&gt;  mult(x*x, n/2)
      }
  }
  </code></pre>
  
  <p>The compilation error is:  </p>
  
  <pre><code>&lt;console&gt;:28: error: could not optimize @tailrec annotated method mult: 
  it contains a recursive call not in tail position
               y *  mult(x*x,(n-2)/2)
                 ^
  </code></pre>
  
  <p>So .. given that the recursive call <strong>is</strong> the last entry - I presume there is an issue with the product y * (tail recursive clause) ?  How to structure this properly ?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Here is a modified version of the accepted answer - in which I was lazy and just put a third accumulator within the called method . </p>
  
  <pre><code>@tailrec def mult(x: Double, n:Int, accum: Double = 1.0) : Double = {
          n match {
        case 0 =&gt; accum
        case 1 =&gt; accum * x
        case _ if ((n &amp; 0x01) != 0) =&gt;  mult(x*x, (n-1)/2, x * accum)
        case _ =&gt;  mult(x*x, n/2, accum)
        }
    }
  
  mult: (x: Double, n: Int, accum: Double)Double
  </code></pre>
  
  <p>Try it out:</p>
  
  <pre><code>scala&gt; mult(2, 7)
  res0: Double = 128.0
  
  scala&gt; mult(2, 8)
  res1: Double = 256.0
  </code></pre>