3 ms·
> Can't any tail call be rewritten as a loop? No. In general tail calls cannot be rewritten into loops.
by tonyg 2y ago
> Can't any tail call be rewritten as a loop?
No. In general tail calls cannot be rewritten into loops.
- cobbal 2y agoMore specifically, tail recursion is usually easy to turn into a loop. Tail calls can be difficult to turn into loops when they call a different function, or worse a function passed in as a variable.
- eru 2y agoTo give the standard example: Consider a state machine where each state is a function, and you transition into a different state by tail-calling another function. State machines can have arbitrarily complicated graphs, that would be hard to put into a simple loop. (However, you can do something like a 'trampoline' to remove the mutual recursion.)