Is there a use case for something like this?
Is there a use case for something like this?
If you want an iterative function, write one. It's not harder than writing a recursive one (although sometimes a bit less readable).
Writing an iterative function is also both faster than the recursive function, and much faster than the hack.
Still a neat hack, though.
[1] http://josf.info/blog/2014/03/21/getting-acquainted-with-clo...
Then you have other problems, where the recursive solution is actually not super easy to understand why it "works" immediately (think, balanced paren generation) and going on to create an iterative solution, while not insanely hard, is not something super obvious.... what's your condition to stop iteration, again?
Maybe I'm thinking about that the wrong way, I'd love to learn more about it!
That problem is closely related to tree traversal, anyway, I should fool around with those two ideas a bit more to properly understand.
Like I said, it is sometimes a bit less readable (tree-walking is a good example of such case), but at the same time, what the code actually does is much clearer. You have no hidden costs, and the code is easier to optimize this way.
You mention a case where you do not fully understand why the recursive solution works, in which case you obviously can't easily write an iterative solution. However, in this case, you are poorly equipped to make any implementation, recursive or iterative.
Was more of an interesting challenge personally.
We can do it for general JS programs. If you are willing to compile Python to JS, you can transparently use our compiler to get heap bounded stacks.