r/ProgrammingLanguages • u/gofl-zimbard-37 • Jan 18 '26
Why not tail recursion?
In the perennial discussions of recursion in various subreddits, people often point out that it can be dangerous if your language doesn't support tail recursion and you blow up your stack. As an FP guy, I'm used to tail recursion being the norm. So for languages that don't support it, what are the reasons? Does it introduce problems? Difficult to implement? Philosophical reasons? Interact badly with other feathers?
Why is it not more widely used in other than FP languages?
76
Upvotes
View all comments
Show parent comment
-5
u/edwbuck Jan 18 '26
They don't create new stack frames, that's why it's called tail-optimized recursion.
Instead, when entering the function "the next" time, it takes the output values and copies them into the same frame it just used, adjusts the instruction pointer back to the beginning of the function's assembly and continues processing using the same stack frame it used before.
This means that when you debug such a thing, it has one function call in its call stack with the input values of the function changing for each execution. This can rob one of whatever utility the other stack frames might have provided, including how many times it was called.
Some languages do additional work to attempt to restore some of the debugging features present in non-tail-call optimized systems for tail-call optimized systems, but they can never be fully restored, or it won't be tail call optimization.