Functional Programming in Scala, chapter 2
I completed the chapter two of the book, pretty basic exercises but very good to brush up some important concepts of functional programming such as recursion, currying, function composition.
Pretty enjoyed it, interesting that Scala provides an annotation for a function that is tail recursive
def factorial(n: Int): Int = {
@tailrec
def go(n: Int, acc: Int): Int = {
if(n <= 0) acc
else go(n-1, n * acc)
}
go(n, 1)
}
A function is tail recursive if is returning the result of the recursive call directly, without doing anything else.
It’s important to say that if a function is annotated in this way and the compiler can’t perform a tail call elimination the compiler will give us an error.
Here the code related to this chapter: