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
93
votes
6 answers

Calling a javascript function recursively

I can create a recursive function in a variable like so: /* Count down to 0 recursively. */ var functionHolder = function (counter) { output(counter); if (counter > 0) { functionHolder(counter-1); } } With this,…
Samthere
  • 1,083
  • 1
  • 8
  • 12
92
votes
5 answers

Recursive function to generate multidimensional array from database result

I'm looking to write a function that takes an array of pages/categories (from a flat database result) and generates an array of nested page/category items based on the parent ids. I would like to do this recursively, so that any level of nesting can…
David Hemphill
  • 1,092
  • 1
  • 8
  • 9
91
votes
3 answers

Using self.xxxx as a default parameter - Python

I'm trying to simplify one of my homework problems and make the code a little better. What I'm working with is a binary search tree. Right now I have a function in my Tree() class that finds all the elements and puts them into a list. tree =…
chrisheinze
  • 1,129
  • 2
  • 9
  • 14
87
votes
3 answers

Recursion schemes for dummies?

I'm looking for some really simple, easy-to-grasp explanations of recursion schemes and corecursion schemes (catamorphisms, anamorphisms, hylomorphisms etc.) which do not require following lots of links, or opening a category theory textbook. I'm…
Robin Green
  • 32,079
  • 16
  • 104
  • 187
86
votes
10 answers

Searching for file in directories recursively

I have the following code to recursively search for files through a directory, which returns a list of all xml files to me. All works well, except that xml files in the root directory are not included in the list. I understand why, since the first…
Paul
  • 891
  • 1
  • 6
  • 10
86
votes
17 answers

Can a lambda function call itself recursively in Python?

A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? …
dsimard
86
votes
6 answers

Inheritance and recursion

Suppose we have the following classes: class A { void recursive(int i) { System.out.println("A.recursive(" + i + ")"); if (i > 0) { recursive(i - 1); } } } class B extends A { void recursive(int i)…
raupach
  • 3,092
  • 22
  • 30
85
votes
1 answer

Can lambda functions be recursive?

Possible Duplicate: Recursive lambda functions in c++0x Here is a plain old recursive function: int fak(int n) { return (n <= 1) ? 1 : n * fak(n - 1); } How would I write such a recursive function as a lambda function? [](int n) { return (n…
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
84
votes
5 answers

Is it possible to make a recursive closure in Rust?

This is a very simple example, but how would I do something similar to: let fact = |x: u32| { match x { 0 => 1, _ => x * fact(x - 1), } }; I know that this specific example can be easily done with iteration, but I'm…
Undeterminant
  • 1,210
  • 1
  • 8
  • 14
82
votes
10 answers

Writing foldl using foldr

In Real World Haskell, Chapter 4. on Functional Programming: Write foldl with foldr: -- file: ch04/Fold.hs myFoldl :: (a -> b -> a) -> a -> [b] -> a myFoldl f z xs = foldr step id xs z where step x g a = g (f a x) The above code confused me a…
ylzhang
  • 1,108
  • 1
  • 8
  • 13
81
votes
14 answers

How does the fibonacci recursive function "work"?

I'm new to Javascript and was reading up on it, when I came to a chapter that described function recursion. It used an example function to find the nth number of the Fibonacci sequence. The code is as follows: function fibonacci(n) { if (n <…
opes
  • 1,778
  • 1
  • 16
  • 22
81
votes
6 answers

What's the explanation for Exercise 1.6 in SICP?

I'm just beginning to work through SICP (on my own; this isn't for a class), and I've been struggling with Exercise 1.6 for a couple of days and I just can't seem to figure it out. This is the one where Alyssa re-defines if in terms of cond, like…
Alex Basson
  • 10,967
  • 6
  • 29
  • 44
79
votes
6 answers

DataAnnotations: Recursively validating an entire object graph

I have an object graph sprinkled with DataAnnotation attributes, where some properties of objects are classes which themselves have validation attributes, and so on. In the following scenario: public class Employee { [Required] public string…
Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220
79
votes
3 answers

Recursive ConcurrentHashMap.computeIfAbsent() call never terminates. Bug or "feature"?

Some time ago, I've blogged about a Java 8 functional way of calculating fibonacci numbers recursively, with a ConcurrentHashMap cache and the new, useful computeIfAbsent() method: import java.util.Map; import…
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
79
votes
9 answers

Functional Programming - Lots of emphasis on recursion, why?

I am getting introduced to Functional Programming [FP] (using Scala). One thing that is coming out from my initial learnings is that FPs rely heavily on recursion. And also it seems like, in pure FPs the only way to do iterative stuff is by writing…
peakit
  • 28,597
  • 27
  • 63
  • 80