views:

55

answers:

3

Many languages (such as python) have a set maximum recursion depth. I realize you can change that depth, or simply not write recursive functions altogether, but if you do write a recursive function and you hit that maximum recursion depth, how would you prepare for and handle that?

+1  A: 

The only thing you really can do at that point is to let the user know that something has gone wrong and the task cannot be performed as designed.

Ignacio Vazquez-Abrams
+2  A: 

Have a parameter in the function signature that gets incremented for each call. When it gets near the maximum recursion depth, do something before it is reached.

Here is a ruby-ish pseudo code example:

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
chiborg
A: 

I think the best way is to avoid writing recursive code that has any chance of reaching the maximum depth. There's always a way to re-write a recursive algorithm as an iterative one, so just do that.

If you're dead set on writing recursive code that may hit the limit, then write a backup iterative version, catch the recursion exceeded exception and switch to the iterative one.

Skilldrick