How to handle maximum recursion depth?

Many languages ​​(e.g. python) have a given maximum recursion depth. I understand that you can change this depth or just not write recursive functions at all, but if you write a recursive function and you press this maximum recursion depth, how would you prepare and process it?

+4
source share
3 answers

Have a parameter in the function signature that gets incremented for each call. When it approaches the maximum depth of the recursion, do something up .

Here is an example of the ruby-ish pseudocode:

def my_recursive_function(current_depth) # do stuff if current_depth >= MAX_RECURSION_LIMIT # throw exception, or output helpful information or return default value else my_recursive_function(current_depth+1) end end 
+3
source

The only thing you can really do at this point is to let the user know that something went wrong and the task cannot be completed as planned.

+1
source

I think the best way is not to write recursive code that has a chance to reach maximum depth. There is always a way to rewrite a recursive algorithm as iterative, so just do it.

If you are dead by writing a recursive code that can exceed the limit, write an iterative version of the backup, catch the exception from recursion and switch to iterative.

+1
source

All Articles