dustinboettcher
dustinboettcher

Reputation: 515

Recursive to Tail-recursive in scala

I have the following code

object TailRec
{
    def func1(n:Int) : Int =
    {
        if (n < 10)
            func2(n)
        else
            func1(n/10) + func2(n % 10)
    }

    def func2(n: Int) : Int =
    {
        @tailrec def _func2(n: Int, result: Int): Int =
        {
            if (n <= 1)
                result
            else
                _func2(n-1,n*result)
        }
        _func2(n,1)
    }

    def test(n: Int) : Boolean =
    {
        if (n > 2)
            n == func1(n)
        else
            false
    }

}

I managed to rewrite func2 but I am not quite sure how to convert the bool function. I thought about match and case but I still need to call func1 to get the result for comparison. The other problem is how to break up the double function call in func1 itself. Any hints?

Upvotes: 0

Views: 189

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

You have already converted func2 into tail-recursive form. Similarly, using an additional accumulator, you can convert func1 into a tail-recursive form (I have modified the interface of func1, but you could also create another inner helper function). Since test isn't recursive, nothing has to be done here.

import scala.annotation.tailrec

object TailRec {
  @tailrec def func1(n:Int, acc: Int): Int = {
    if (n < 10) func2(n)
    else func1(n / 10, acc + func2(n % 10))
  }

  def func2(n: Int): Int = {
    @tailrec def _func2(n: Int, result: Int): Int = {
      if (n <= 1) result
      else _func2(n-1,n*result)
    }
    _func2(n,1)
  }

  def test(n: Int): Boolean = (n > 2) && (n == func1(n, 0))
}

Upvotes: 3

Related Questions