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.
This gives you access to free test cases & hints for all our 89 published algorithms as well as our installation-free Scala IDE.
You can then choose to subscribe to "Scala Algorithms Unlimited", which gets you access to every current and upcoming algorithm solution. We use Stripe so your data is safe.
We will e-mail you at most once per week with new algorithms and relevant content. Your data is protected and unsubscribing is straightforward.