In Scala, tail recursion enables you to rewrite a mutable structure such as a while-loop, into an immutable algorithm.
Tail recursion always has a recursive call in a "final" position, ie you can only either return a result (exit the function), or return another call to self-function
In canonical form, the immutable form gets compiled down to the mutable form,
becomes (after a stage of compilation):
This transformation can also be performed the other way round, as to give you a pure immutable solution
What are the benefits of tail recursion?
Tail recursion in Scala utilises a principle known as tail-call optimisation. It allows one to write iterative algorithms (that would otherwise would be complicated while-loops) in immutable form.
What are the benefits of immutability?
It becomes easier to reason about your code, and you always know that you can re-run a function as manytimes as you wish without causing unexpected side effects.
But really, can anything be written in this shape?
Anything that is iterative in nature can, so long as it can be represented in the canonical form.