5 ms·
Universal solution for breaking recursion loop
- lutusp 14y agoYes, just like in the textbooks -- count depth and bail. > One of the biggest problem which developer are facing is breaking recursive function. Not really any kind of problem. > It is very hard and tricky to impose limit on recursive loop. It is very easy. Not tricky at all. An easier way than yours: recursive_function(n) { if(n < 5) { recursive_function(n+1); } }
- justplay 14y agoProblem is you have to worry and take special care of infinite loop of recursive function. And of course your solution is valid but not universal. Everytime you have to think of its minimal condition where it may not work. This solution gaureente that you simply put this condition and apply your logic, here you never meet infinite loop condition.
- lutusp 14y ago> Problem is you have to worry and take special care of infinite loop of recursive function. Not really. It's too easy to do right. > And of course your solution is valid but not universal. It is both valid and universal -- it doesn't require the static variable your method requires, which is a bad idea, and it doesn't require mutable variables, which are disallowed in functional languages. > Everytime you have to think of its minimal condition where it may not work. It always works. Always. It never fails. Never. > This solution gaureente that you simply put this condition and apply your logic, here you never meet infinite loop condition. 1. A recursion is not a "loop", infinite or otherwise. 2. Frankly, your solution is designed badly -- it requires a static variable, which prevents it from working in a case where this syntax is disallowed. It also requires the use of mutable variables, which are disallowed in functional languages. Python: def recursive_function(n = 0): print '%sEntering recursion %d' % (' ' * n,n) if(n < 10): recursive_function(n+1) print '%sLeaving recursion %d' % (' ' * n,n) recursive_function() Output: Entering recursion 0 Entering recursion 1 Entering recursion 2 Entering recursion 3 Entering recursion 4 Entering recursion 5 Entering recursion 6 Entering recursion 7 Entering recursion 8 Entering recursion 9 Entering recursion 10 Leaving recursion 10 Leaving recursion 9 Leaving recursion 8 Leaving recursion 7 Leaving recursion 6 Leaving recursion 5 Leaving recursion 4 Leaving recursion 3 Leaving recursion 2 Leaving recursion 1 Leaving recursion 0