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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With