Hacker News new | past | comments | ask | show | jobs | submit login
Universal solution for breaking recursion loop (paritoshwords.tumblr.com)
1 point by justplay on Oct 18, 2012 | hide | past | favorite | 3 comments



Yes, 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);
      }
    }


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


> 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




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: