r/ProgrammingLanguages • • 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

117 comments sorted by

View all comments

Show parent comment

4

u/joonazan Jan 18 '26

Tail recursion is not just a different way to write a loop. It allows you to write for instance a state machine as functions that jump to each other. Generating the same assembly using a loop isn't possible. It would require at least goto.

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).

1

u/joonazan Jan 19 '26

Yes, switch-case interpreters perform poorly. A large switch is too big for compilers. Theoretically a compiler could optimize it but tail calls guarantee sensible behaviour.