Comment by tonyg

1 year ago

> Can't any tail call be rewritten as a loop?

No. In general tail calls cannot be rewritten into loops.

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

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