van dench February 2016

Real Life uses for Function Recursion

Are there any times where it is better to use function recursion for a task instead of any other methods? By function recursion I am referring to:

function myFunc() {
  var x = myFunc();
}

Answers


Parthian Shot February 2016

Well, there are a few reasons I can think of.

  • Recursion is often easier to understand than a purely iterative solution. For example, in the case of recursive-descent parsers.

  • In compilers with support for tail call optimization, there's no additional overhead to using recursion over iteration, and it often results in fewer lines of code (and, as a result, fewer bugs).


Simon Kraemer February 2016

First of all your example doesn't make any sense. The way you wrote it would just lead to an endless loop without any result ever.

A "real" function would more look like this:

int factorial(int value)
{
    if (value == 0)
      return 1;
    else
      return value * factorial(value - 1);
}

Of course you could accomplish the same thing with a loop (which might even be better, especially if the function call incurs the penalty of a stack frame). Usually, when people use recursion they do so because it's easier to read (for certain problem domains).

Post Status

Asked in February 2016
Viewed 1,321 times
Voted 4
Answered 2 times

Search




Leave an answer