Can every recursion be converted into iteration?

2018-12-31 06:26发布

A reddit thread brought up an apparently interesting question:

Tail recursive functions can trivially be converted into iterative functions. Other ones, can be transformed by using an explicit stack. Can every recursion be transformed into iteration?

The (counter?)example in the post is the pair:

(define (num-ways x y)
  (case ((= x 0) 1)
        ((= y 0) 1)
        (num-ways2 x y) ))

(define (num-ways2 x y)
  (+ (num-ways (- x 1) y)
     (num-ways x (- y 1))

18条回答
查无此人
2楼-- · 2018-12-31 06:38

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

The below cases are among the easy:

查看更多
不流泪的眼
3楼-- · 2018-12-31 06:39

All computable functions can be computed by Turing Machines and hence the recursive systems and Turing machines (iterative systems) are equivalent.

查看更多
公子世无双
4楼-- · 2018-12-31 06:39

Have a look at the following entries on wikipedia, you can use them as a starting point to find a complete answer to your question.

Follows a paragraph that may give you some hint on where to start:

Solving a recurrence relation means obtaining a closed-form solution: a non-recursive function of n.

Also have a look at the last paragraph of this entry.

查看更多
素衣白纱
5楼-- · 2018-12-31 06:39

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
查看更多
大哥的爱人
6楼-- · 2018-12-31 06:42

Appart from the explicit stack, another pattern for converting recursion into iteration is with the use of a trampoline.

Here, the functions either return the final result, or a closure of the function call that it would otherwise have performed. Then, the initiating (trampolining) function keep invoking the closures returned until the final result is reached.

This approach works for mutually recursive functions, but I'm afraid it only works for tail-calls.

http://en.wikipedia.org/wiki/Trampoline_(computers)

查看更多
不流泪的眼
7楼-- · 2018-12-31 06:44

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

查看更多
登录 后发表回答