Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which recursive functions cannot be rewritten using loops? [duplicate]

Tags:

recursion

As far as I know, most recursive functions can be rewritten using loops. Some may be harder than others, but most of them can be rewritten.

Under which conditions does it become impossible to rewrite a recursive function using a loop (if such conditions exist)?

like image 755
Hosam Aly Avatar asked Feb 10 '09 09:02

Hosam Aly


People also ask

Can all recursive functions be rewritten as loops?

So, yes all-recursive code can be converted to iteration.

Which function Cannot use recursion?

Explanation: There is nothing recursion can compute that looping can't, but looping takes a lot more plumbing. Therefore, the one thing recursion can do that loops can't is make some tasks super easy.

Can a recursion function always be replaced by iteration?

Every recursive function can be transformed into an iterative function by replacing recursive calls with iterative control constructs and simulating the call stack with a stack explicitly managed by the program.


1 Answers

When you use a function recursively, the compiler takes care of stack management for you, which is what makes recursion possible. Anything you can do recursively, you can do by managing a stack yourself (for indirect recursion, you just have to make sure your different functions share that stack).

So, no, there is nothing that can be done with recursion and that cannot be done with a loop and a stack.

like image 67
Carl Seleborg Avatar answered Oct 11 '22 15:10

Carl Seleborg