Search code examples
scalafunctionrecursionfunctional-programmingtail-recursion

Writing a factorial tail recursive function in Scala


I'm trying to write a tail recursive function in the below way, but the compiler is throwing an error:

Too many arguments for method apply: (v1: Int)Int in trait Function1 else factorial(x-1, x*acc)

I had tried replacing Function1 with Function2 and gave Function2[Int, Int, Int] = new Function2[Int, Int, Int]

But it still threw me the same error. Can someone point out where i'm going wrong?

import scala.annotation.tailrec
var factorial: Function1[Int, Int] = new Function1[Int, Int] {
    @tailrec override def apply (x:Int, acc:Int=1): Int = {
        if (x<=1) acc
        else factorial(x-1, x*acc)
    }
}

factorial(5)

Solution

  • You apply inside Function1 must take only one param, when you are passing two.

    You can rewrite it as follows:

    var factorial: Function1[Int, Int] = new Function1[Int, Int] {
      def apply (x:Int): Int = {
        @tailrec def loop(x: Int, acc: Int = 1): Int = {
          if (x<=1) acc
          else loop(x-1, x*acc)
        }
        loop(x)
      }
    }