Dimitri
Dimitri

Reputation: 8280

Tail Recursion and Side effect

I am actually learning scala and I have a question about tail-recursion. Here is an example of factorial with tail recursion in scala :

    def factorial(n: Int): Int = {

    @tailrec
    def loop(acc: Int, n: Int): Int = {
      if (n == 0) acc
      else loop(n * acc, n - 1)
    }
    loop(1, n)
  }              

My question is updating the parameter, acc as we do it in the function loop can be considered as a side effect? Since in FP, we want to prevent or diminish the risk of side effect.

Maybe I get this wrong, but can someone explain to me this concept.

Thanks for your help

Upvotes: 3

Views: 475

Answers (1)

Péter Török
Péter Török

Reputation: 116266

You aren't actually changing the value of any parameter here (as they are vals by definition, you couldn't, even if you wanted to).

You are returning a new value, calculated from the arguments passed in (and only those). Which, as @om-nom-nom pointed out in his comment, is the definition of pure function.

Upvotes: 7

Related Questions