Home > Net >  Why does @tailrec not permit this function?
Why does @tailrec not permit this function?

Time:04-06

I want to do ln(N!) in Scala with tailrec

  @tailrec
  final def recursiveLogN(n: Int): Double = {
    if (n <= 1) {
      return 0
    }
    Math.log(n)   recursiveLogN(n - 1)
  }

The compile error:

could not optimize @tailrec annotated method recursiveLogN: it contains a recursive call not in tail position
    Math.log(n)   recursiveLogN(n - 1)

CodePudding user response:

The recursive call should be the last method call, the way your snippet is written it is just part of the last expression.

It can be rewritten to something like:


  @tailrec
  final def recursiveLogN(n: Int, accum: Double = 0): Double = {
    if (n <= 1) {
      return accum
    }
   recursiveLogN(n - 1, accum  Math.log(n))
  }

And then tail call elimination will be possible

  • Related