Questions tagged [recursion]

Recursion is a kind of function call in which a function calls itself. Such functions are also called recursive functions. Structural recursion is a method of problem solving where the solution to a problem depends on solutions to smaller instances of the same problem.

The term, "recursion," describes a code structure in which a function potentially calls itself. Such functions are also called recursive functions.

Structural recursion is a method of problem solving where the solution to a problem depends on solutions to smaller or simpler instances of the same problem.

In computer science, a recursive function calls itself directly or indirectly, for example when several mutually recursive functions are working together. A recursion cannot be endless; each recursion level requires memory. This is the reason why recursive functions need conditions to not call themselves; hence, a recursive function potentially calls itself but not unconditionally.

Some functional programming languages do not define any looping constructs, but rely solely on recursion to repeatedly call code. Likewise, in languages that do provide loops, it is possible for any recursive function to be written using loops without requiring recursion.

This defines two basic approach to repeatedly call some piece of code.

  • Iterative approach (Using loop constructs)
  • Recursive approach (Using recursion)

In addition to program code, recursion can also occur in data structures, where a nested object or array may contain a reference to an element further up the data tree.

Examples in several languages

C

void recursiveFunction(int num) {
   if (num < 4)
      recursiveFunction(num + 1);
   printf("%d\n", num);
}

C++

void recursiveFunction(int num) {
   if (num < 4)
      recursiveFunction(num + 1);
   std::cout << num;
}

Java

public static int factorial(int N) { 
   if (N == 1) return 1; 
   return N * factorial(N-1); 
}

OCaml

let rec factorial n =
    if n <= 1 then 1 else n * factorial (n - 1)

Haskell

factorial n = if n == 0 then 1 else n * factorial (n - 1)

Perl

sub factorial {
    my $n = shift;
    return 1 if $n == 1;
    return $n * factorial($n - 1);
}

Haxe

function factorial(num:Int) { 
   if (num == 1) return 1; 
   return num * factorial(num - 1); 
}

Python (2 or 3)

def factorial(n):
    return 1 if n <= 1 else n * factorial(n - 1)

Tag usage

should be used for programming-related problems when using recursion in any programming language. On Stack Overflow, please avoid theoretical questions such as "how does recursion work?"

References

Further information

46639 questions
116
votes
55 answers

Real-world examples of recursion

What are real-world problems where a recursive approach is the natural solution besides depth-first search (DFS)? (I don't consider Tower of Hanoi, Fibonacci number, or factorial real-world problems. They are a bit contrived in my mind.)
redfood
  • 659
  • 2
  • 8
  • 11
112
votes
7 answers

Can generators be recursive?

I naively tried to create a recursive generator. Didn't work. This is what I did: def recursive_generator(lis): yield lis[0] recursive_generator(lis[1:]) for k in recursive_generator([6,3,9,1]): print(k) All I got was the first item…
Aguy
  • 7,851
  • 5
  • 31
  • 58
109
votes
11 answers

Convert a series of parent-child relationships into a hierarchical tree?

I have a bunch of name-parentname pairs, that I'd like to turn into as few heirarchical tree structures as possible. So for example, these could be the pairings: Child : Parent H : G F : G G : D E : D A : E B : C C : E …
Eric
  • 95,302
  • 53
  • 242
  • 374
109
votes
9 answers

One-liner to recursively list directories in Ruby?

What is the fastest, most optimized, one-liner way to get an array of the directories (excluding files) in Ruby? How about including files?
Lance
  • 75,200
  • 93
  • 289
  • 503
109
votes
4 answers

Why does my recursive function return None?

I have this function that calls itself: def get_input(): my_var = input('Enter "a" or "b": ') if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') get_input() else: return…
Cate
  • 1,227
  • 2
  • 9
  • 7
108
votes
33 answers

Reversing a linked list in Java, recursively

I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called AddressList, containing simple nodes called ListNode). The catch is that everything would have to be done with recursive…
sdellysse
  • 39,108
  • 9
  • 25
  • 24
105
votes
5 answers

Are functions in JavaScript tail-call optimized?

I have been trying to understand Tail call optimization in context of JavaScript and have written the below recursive and tail-recursive methods for factorial(). Recursive: function factorial (n) { if (n < 2) { return 1; } else { return…
Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
105
votes
12 answers

Node.js - Maximum call stack size exceeded

When I run my code, Node.js throws a "RangeError: Maximum call stack size exceeded" exception caused by too many recursive calls. I tried to increase Node.js stack size by sudo node --stack-size=16000 app, but Node.js crashes without any error…
user1518183
  • 4,651
  • 5
  • 28
  • 39
104
votes
3 answers

Recursion using yield

Is there any way to mix recursion and the yield statement? For instance, a infinite number generator (using recursion) would be something like: def infinity(start): yield start # recursion here ... >>> it = infinity(1) >>> next(it) 1 >>>…
juliomalegria
  • 24,229
  • 14
  • 73
  • 89
102
votes
8 answers

How to get all files under a specific directory in MATLAB?

I need to get all those files under D:\dic and loop over them to further process individually. Does MATLAB support this kind of operations? It can be done in other scripts like PHP,Python...
Gtker
  • 2,237
  • 9
  • 29
  • 37
102
votes
3 answers

Python: using a recursive algorithm as a generator

Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer…
Federico A. Ramponi
  • 46,145
  • 29
  • 109
  • 133
96
votes
1 answer

What are paramorphisms?

Reading through this classic paper, I'm stuck on paramorphisms. Unfortunately the section is quite thin, and the Wikipedia page doesn't say anything. My Haskell translation is: para :: (a -> [a] -> b -> b) -> b -> [a] -> b para f base = h where …
Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
96
votes
11 answers

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

The unzip command doesn't have an option for recursively unzipping archives. If I have the following directory structure and archives: /Mother/Loving.zip /Scurvy/Sea Dogs.zip /Scurvy/Cures/Limes.zip And I want to unzip all of the archives into…
chuckrector
  • 1,471
  • 1
  • 12
  • 9
95
votes
6 answers

How to render a tree in Twig

I would like to render a tree with an undetermined depth (children of children of children, etc.). I need to loop through the array recursively; how can I do this in Twig?
T-RonX
  • 1,053
  • 1
  • 9
  • 7
94
votes
1 answer

Python: Maximum recursion depth exceeded

I have the following recursion code, at each node I call sql query to get the nodes belong to the parent node. here is the error: Exception RuntimeError: 'maximum recursion depth exceeded' in
add-semi-colons
  • 18,094
  • 55
  • 145
  • 232