Can every recursion be converted into iteration?

前端 未结 17 2309
遥遥无期
遥遥无期 2020-11-22 01:59

A reddit thread brought up an apparently interesting question:

Tail recursive functions can trivially be converted into iterative functions. Other one

相关标签:
17条回答
  • 2020-11-22 02:17

    Yes, using explicitly a stack (but recursion is far more pleasant to read, IMHO).

    0 讨论(0)
  • 2020-11-22 02:17

    Here is an iterative algorithm:

    def howmany(x,y)
      a = {}
      for n in (0..x+y)
        for m in (0..n)
          a[[m,n-m]] = if m==0 or n-m==0 then 1 else a[[m-1,n-m]] + a[[m,n-m-1]] end
        end
      end
      return a[[x,y]]
    end
    
    0 讨论(0)
  • 2020-11-22 02:23

    Removing recursion is a complex problem and is feasible under well defined circumstances.

    The below cases are among the easy:

    • tail recursion
    • direct linear recursion
    0 讨论(0)
  • 2020-11-22 02:24

    Recursion is implemented as stacks or similar constructs in the actual interpreters or compilers. So you certainly can convert a recursive function to an iterative counterpart because that's how it's always done (if automatically). You'll just be duplicating the compiler's work in an ad-hoc and probably in a very ugly and inefficient manner.

    0 讨论(0)
  • 2020-11-22 02:24

    Yes, it's always possible to write a non-recursive version. The trivial solution is to use a stack data structure and simulate the recursive execution.

    0 讨论(0)
  • 2020-11-22 02:26

    In principle it is always possible to remove recursion and replace it with iteration in a language that has infinite state both for data structures and for the call stack. This is a basic consequence of the Church-Turing thesis.

    Given an actual programming language, the answer is not as obvious. The problem is that it is quite possible to have a language where the amount of memory that can be allocated in the program is limited but where the amount of call stack that can be used is unbounded (32-bit C where the address of stack variables is not accessible). In this case, recursion is more powerful simply because it has more memory it can use; there is not enough explicitly allocatable memory to emulate the call stack. For a detailed discussion on this, see this discussion.

    0 讨论(0)
提交回复
热议问题