Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 319
Dimitri Avatar asked Dec 08 '25 13:12

Dimitri


1 Answers

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.

like image 150
Péter Török Avatar answered Dec 10 '25 09:12

Péter Török