Is recursion generally considered an obsolete passing method compared to using a stack?

I read in several places where people prefer to use Stack instead of recursion. Is it because recursion is seen as an obsolete way to get work, or are both methods equally applicable in different contexts?

+3
source share
5 answers

Iteration is often faster / has less overhead than recursion. With recursion, we implicitly use machine stacks as our stack — we get it “for free” —but we pay for expensive function calls (and associated machine stack management).

But recursive functions are often more intuitive to write and read.

, , , , .

+10

. . - . - , .

., , question. : n- .

, -

0,1,1,2,3,5,8,13, ...

, F n= F n-1 + F n-2.

:
F (0) = 0 F (1) = 1
:
F (n) = F (n-1) + F (n-2)

, F (0) = 0, F (1) = 1, F (2) = F (0) + F (1) = 1 ..

( C ):

int fib(int n) {
    /* we'll ignore possible negative arguments, see Wikipedia */
    switch(n) {
       case 0: return 0; break;
       case 1: return 1; break;
       default: return fib(n-1)+fib(n-2); break;
    }
}

, ?

, C . (, , FORTRAN, , ). FORTRAN, , .

+15

, fishlips.

Stack - recursion

: ?

Tail-Recursion ( ):

public class TailTest
{   
    public static void Main()
    {       
        TailTest f = new TailTest();
        f.DoTail(0);
    }

    public void DoTail(int n)
    {       
        int v = n + 1;      
        System.Console.WriteLine(v);    

        DoTail(v);   // Tail-Recursive call
    }
}
+6

/, ( (TCO)), , , .

, /, , , / .

(This is a bit broader, but overall, I would in no way call recursion "deprecated.")

+4
source

No, I think that modern developers should emphasize readability and ease of maintenance for a few milliseconds.

If the IS problem is recursive, I fully recommend your solution BE recursive.

In addition, you may introduce some suspicious errors trying to force an iterative / complex solution.

+3
source

Source: https://habr.com/ru/post/1707222/


All Articles