Open In App

Recursive lambda expressions in C++

Last Updated : 17 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Share
12 Likes
Like
Report

A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

A recursive function is a kind of loop structure only. The difference is it maintains a memory stack on its own. Obviously, it must have a break condition like for and while loop. Hence, the recursive function has the following structure-

function name(arguments)
{
    a base case (a breaking condition)   
    recursive code (the actual logic)
}
int fact(int n)
{
    // Base Case
    if (n < = 1)
        return 1;
    else    
        return n * fact(n - 1);    
}

C++ 11 introduced lambda expressions to allow us to write an inline function that can be used for short snippets of code that are not going to be reused and not worth naming. In its simplest form, the lambda expression can be defined as follows:

[ capture clause ] (parameters) -> return-type  
{   
   definition of method   
} 

Program 1:

Below is the program for the lambda expressions in the sort() method in C++:


Output
5 4 3 2 1 

Time complexity: O(nlogn)

Auxiliary Space: O(1)

Explanation: Here, the instant lambda function is used, which cannot be used in another sorting method, i.e., the same code needs to be written again. This lambda expression exists only during the execution of the sort() method. But it is possible to store the lambda expression in a variable (better to call it a function) as well, like below. By storing it, it can be used further, and of course, perform recursion also.  

Program 2:


Output
5 4 3 2 1 

Time complexity: O(nlogn)

Auxiliary Space: O(1)

Explanation: Here, auto cmp is the lambda stored function that can be used in as many sorting methods.

Recursion Using Lambda: Let's discuss the concept of recursion and lambda expressions together by considering the recursive function below:

Program 3:


Output
5 4 3 2 1 

Time complexity: O(logn)

Auxiliary Space: O(logn)

Explanation: Above is the function which prints the digits of a number in reverse order, using recursion. The same can be done using the lambda expression.

Program 4:

Below is the C++ program to implement the above code using lambda expressions: 

// C++ program to implement
// the above approach
#include <iostream>
using namespace std;

// Driver code
int main()
{
    int n = 12345;

    // Recursive lambda function to
    // print the digits of a number
    auto printReverse = [&]() {
        if (n == 0)
            return;
        cout << n % 10;
        n = n / 10;
        printReverse();

        // As it is a part of main body,
        // semicolon is must
    };

    printReverse();
    return 0;
}

Output: 

Error
Oops, the function, defined using auto return type, must be deducted first (Compiler must be able to determine whether the return type auto can be converted into void or int or something else) 

Explanation: Here, how the function is going to recognize the variable n, even if it is not passed as an argument. A lambda with an empty capture clause [ ] can access only those variables which are local to it. Here, the capture close [&] is used, which allows the function to access the variable n ( The actual value of variable n is being changed). There are two ways to resolve the error above:

1. By passing the function itself, to the function argument:

Below is the C++ program to implement the above concept:

Program 5: 


Output
5 4 3 2 1 

Time complexity: O(logn)

Auxiliary Space: O(logn)

2. By declaring the function first:

Declaring a function means declaring its name and parameters type in order to inform a compiler that there is a function named xyz, which will write its body later.

Program 6:

Below is the C++ program to implement the above concept: 


Output
Hello I am learning how to declare a function

Time complexity: O(1)

Auxiliary Space: O(1)

Program 7:

Since it is a lambda function, there must be some unique way of declaring the function. Below is the C++ program for the same: 


Output
5 4 3 2 1 

Time complexity: O(logn)

Auxiliary Space: O(logn)

Explanation: In the above code, first, the function printReverse is declared, then we have defined its body. Instead of that, we can directly declare the function and its body along with, which is known as defining a function. Below is the C++ program to implement the above approach:

Program 8:


Output
5 4 3 2 1 

Time complexity: O(logn)

Auxiliary Space: O(logn)

Examples: Below are some examples of recursive functions using lambda expressions.

Program 9: 


Output
720
120

Time complexity: O(2n)

Auxiliary Space: O(n)

Explanation: In the factorial function, n is directly accessed using the [&] capture clause. In the factorial2 function, n is passed as an argument. Hence, there is no need for the [&] clause.

Program 10:


Output
Found on index 4

Time complexity: O(logn)

Auxiliary Space: O(1)


Article Tags :
Practice Tags :

Similar Reads