Arnaud learns Scala - part 2
One of the basics of functional programming: tail recursion – or how to write an iterative code that looks recursive.
Tail-recursive factorial
Scala By Example describes tail recursion and asks the reader to design a tail-recursive version of the factorial function.
That is easy with the help of a nested function which acts as an accumulator:
Note: @tailrec
only ensures the nested function is recognized as a tail-recursive function but
it isn’t required.
Performance figures
In order to show the runtime difference let me compare the performance between the simply-recursive version and the tail-recursive version, the code is:
The output for factorial1 is:
The output for factorial2 is:
Convinced or need to see the bytecode?
Bytecode of the tail-recursive version
The decompiled java code of the tail-recursive version looks like this:
That shows the actual effect of the tail-recursive design.