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
2
u/kohugaly Jan 19 '26
Are you sure? From what I understand, you can implement any state machine with a tagged union of all the states, and a switch-case for the state transitions. Driving the state machine to completion is a matter of invoking the state transitions in a loop, and breaking out of the loop on terminal states.
Whether this would generate the same assembly depends on how the switch case in an infinite loop gets compiled and optimized.
Since the loop is infinite, and only contains the switch, the checking of the tag can be moved to end of each branch. At the end of each branch (end of each state transition), the tag of the next state is known at compile time, therefore the lookup in the jump table can be precomputed (ie. it simplifies to a goto).