Creating Recursive Lambdas

Can a lambda call itself recursively?

Yes, a lambda can call itself recursively. However, because lambdas don't have a name by default, you need to use a special technique to achieve this.

The trick is to capture a reference to the lambda itself using a std::function. Here's an example that calculates the factorial of a number using a recursive lambda:

#include <iostream>
#include <functional>

int main() {
  std::function<int(int)> factorial{
    [&factorial](int n) {
      if (n <= 1) {
        return 1;
      } else {
        return n * factorial(n - 1);
      }
    }
  };

  std::cout << "Factorial of 5: "
    << factorial(5) << '\n';
}
Factorial of 5: 120

Here's how this works:

  1. We declare a std::function named factorial. This will hold our lambda.
  2. We initialize factorial with a lambda that takes an integer n and returns an integer.
  3. Inside the lambda, we check the base case (n <= 1). If this is true, we return 1.
  4. If the base case is not met, we return n * factorial(n - 1). This is where the recursion happens.
  5. Importantly, factorial is captured by reference in the lambda. This allows the lambda to call itself through the factorial variable.

When we call factorial(5), it will recursively compute the factorial of 5, which is 120.

This pattern can be used to create recursive lambdas for various tasks. However, it's important to ensure that your recursive lambda has a base case that stops the recursion, otherwise you'll get infinite recursion and a stack overflow.

Also note that recursive lambdas can be less efficient than iterative solutions due to the overhead of function calls. However, they can be useful in situations where a recursive solution is more clear and concise.

Remember that this technique requires capturing the lambda by reference. Be careful not to let the reference outlive the lambda, as this will result in undefined behavior.

Lambdas

An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Capturing Class Members in Lambdas
How can I capture member variables of a class when defining a lambda inside a member function?
Returning Lambdas from Functions
Can I return a lambda from a function? If so, how do I specify the return type?
Using Lambdas in Template Functions
How can I pass a lambda as an argument to a function template?
Using Lambdas as Comparators
Can I use a lambda as a comparator for STL containers and algorithms?
Creating Stateful Lambdas
Is it possible to create a lambda that maintains state across multiple invocations?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant