← Back to context Comment by tonyg 2 years ago > Can't any tail call be rewritten as a loop?No. In general tail calls cannot be rewritten into loops. 2 comments tonyg Reply cobbal 2 years ago 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. eru 2 years ago 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.)
cobbal 2 years ago 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. eru 2 years ago 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.)
eru 2 years ago 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.)
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.)