Search code examples
algorithmrecursionurl-rewritingnon-recursive

Rewriting a recursive function without using recursion


I'm rewriting some existing code in a setting where recursive calls are not easily implemented nor desired. (And in Fortran 77, if you must know.) I've thought about making a stack from scratch to keep track of the calls needed, but this seems kludgy, and I'd rather not allocate memory to an array in cases where the recursion is not deep. (I'm not confident that Fortran 77 supports dynamic array sizing either.)

Any other suggestions for a general solution on how to take an obviously recursive function and rewrite it non-recursively without wasting space on a stack?


Solution

  • If your code uses tail recursion (that is, the function returns the result of every recursive call directly without any other processing) then it's possible to rewrite the function imperatively without a stack:

    function dosomething(a,b,c,d) 
    {
      // manipulate a,b,c,d
      if (condition) 
        return dosomething(a,b,c,d) 
      else
        return something;
    }
    

    Into:

    function dosomething(a,b,c,d) 
    {
      while (true) 
      {
        // manipulate a,b,c,d
        if (condition) continue;
        else return something;
      }
    }
    

    Without tail recursion, using a stack (or a similar intermediary storage) is the only solution.