Evgenii Legotckoi
July 6, 2018, 2:26 p.m.

Cooking lambda functions in C ++ - Part 2 - Recursive lambda functions using the example of factorial calculation

In the previous article , we got acquainted with the structure of lambda functions, and now we'll play with lambdas, calculate the factorial, and consider how the lambda function can be applied for this.

Let's consider for the beginning the usual variant of factorial calculation, and also we will specify that such a recursive function.

Recursive function

A recursive function is that function that calls itself. This means that inside the function there is a call to itself, and infinite recursion can occur if the function code does not have the conditions for exiting recursion.

Here is an example of such an infinite recursive function, the program with which it terminates crash due to overflow of the call stack.

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void infiniteRecursiveFunction()
  6. {
  7. cout << "Hello World!" << endl;
  8. infiniteRecursiveFunction();
  9. }
  10.  
  11. int main()
  12. {
  13. infiniteRecursiveFunction();
  14. return 0;
  15. }

To prevent this from happening, you need to add an exit condition from the recursive function, for example, the achievement of a recursive call count of 100.

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void infiniteRecursiveFunction(int counter = 0)
  6. {
  7. cout << "Hello World!" << endl;
  8. if (counter == 100)
  9. {
  10. return;
  11. }
  12. infiniteRecursiveFunction(counter + 1);
  13. }
  14.  
  15. int main()
  16. {
  17. infiniteRecursiveFunction();
  18. return 0;
  19. }

Now the recursive function will be completed correctly, thanks to the counter, the call stack will not overflow and the program will end without errors.

Factorial

And now let's define what factorial is.

The factorial is the product of natural numbers from 1 to the number itself (including a given number).
The factorial is denoted by the exclamation mark "!".

Examples:

  • 4! = 1 · 2 · 3 · 4 = 24
  • 5! = 1 · 2 · 3 · 4 · 5 = 120

Now write a function for calculating the factorial

  1. long double fact(int N)
  2. {
  3. if(N < 0) // if the user entered a negative number
  4. {
  5. return 0; // return zero
  6. }
  7. else if (N == 0) // if the user entered zero,
  8. {
  9. return 1; // return the factorial from zero, which is 1
  10. }
  11. else // in all other cases
  12. {
  13. return N * fact(N - 1); // we perform recursive function calls
  14. }
  15. }

In this case, the function is written so that the factorial calculation is performed from the largest number and ends with zero. Then the correct exit from the recursion will be performed and the function will return the value of the factorial.

As a result, the code for calculating the factorial will look like this

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. long double fact(int N)
  6. {
  7. if(N < 0) // if the user entered a negative number
  8. {
  9. return 0; // return zero
  10. }
  11. else if (N == 0) // if the user entered zero,
  12. {
  13. return 1; // return the factorial from zero, which is 1
  14. }
  15. else // in all other cases
  16. {
  17. return N * fact(N - 1); // we perform recursive function calls
  18. }
  19. }
  20.  
  21. int main()
  22. {
  23. int N {0};
  24. cout << "Input number for factorial" << endl;
  25. cin >> N;
  26. cout << "Factorial for number " << N << " = " << fact(N) << endl; // fact(N) - function for calculating the factorial.
  27. return 0;
  28. }

The use of recursive lambda functions

And now we apply the recursive lambda function to calculate the factorial.

In modern C ++ standards, there are two options for writing recursive functions:

  • Using std::function
  • Without using std::function

Using std::function

In this case, for the application of lambda recursion, the function should know about its own structure to be able to capture itself by reference, but the lambda function is an anonymous declaration of an object that somehow needs to be made explicit. In this we will help std::function , which will help determine the signature of the lambda function.

  1. #include <iostream>
  2. #include <functional> // We connect the library to use std::function
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int N {0};
  9.  
  10. // Signature declaration via std::function -> std::function<int(int)>
  11. // Function signature int (int)
  12. // [&fact] - Capture the lambda itself
  13. std::function<int(int)> fact = [&fact](int N)
  14. {
  15. if(N < 0) // if the user entered a negative number
  16. {
  17. return 0; // return zero
  18. }
  19. else if (N == 0) // if the user entered zero,
  20. {
  21. return 1; // return the factorial from zero, which is 1
  22. }
  23. else // in all other cases
  24. {
  25. return N * fact(N - 1); // we perform recursive function calls
  26. }
  27. };
  28.  
  29. cout << "Input number for factorial" << endl;
  30. cin >> N;
  31. cout << "Factorial for number " << N << " = " << fact(N) << endl; // fact(N) - function for calculating the factorial.
  32. return 0;
  33. }

The limitation of recursive lambdas is that we can not capture the lambda function until its signature is known. That is, auto can not be used immediately, because auto makes the output of the lambda structure at compile time and if the lambda object was not formed, then we can not capture the lambda, and since it captures itself, but has not yet been compiled, structure does not know anything, and therefore can not capture itself.

Then, std::function comes to the rescue, which allows you to predefine the signature of the lambda function, initialize it with a lambda function, and be used as an invisible link to the same lambda function.

Without using std::function

But this does not mean that you can not do without the explicit use of std::function for recursive functions. In the standard C++14 , it became possible to define the arguments of lambda functions as auto, due to what the lambda function can be passed as an argument to itself by reference. The same recursive lambda function will be obtained, but using only C++ programming language tools.

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. int N {0};
  8.  
  9. // Lambda declaration via auto
  10. // Lambda signature int (auto&, int)
  11. // auto& self - in this argument will be passed to the lambda function to perform itself
  12. auto fact = [](auto& self, int N)
  13. {
  14. if(N < 0) // if the user entered a negative number
  15. {
  16. return 0; // return zero
  17. }
  18. else if (N == 0) // if the user entered zero,
  19. {
  20. return 1; // return the factorial from zero, which is 1
  21. }
  22. else // in all other cases
  23. {
  24. // We call a lambda passing as an argument lambda on the link further in itself
  25. return N * self(self, N - 1); // we perform recursive function calls
  26. }
  27. };
  28.  
  29. cout << "Input number for factorial" << endl;
  30. cin >> N;
  31. // When you first call a lambda, you also need to pass the lambda to itself as an argument
  32. // fact(fact, N)
  33. cout << "Factorial for number " << N << " = " << fact(fact, N) << endl; // fact(N) - function for calculating the factorial.
  34. return 0;
  35. }

Conclusion

To the question of the expediency of applying recursive lambda functions.

It makes no sense to declare a function or method in a class if this function is used in one single place in the code. This will at least complicate the interface of the class, if we write new methods for each sneeze. It is much better to declare a lambda within another method, where it must be executed. This applies to all lambda functions, both conventional and recursive.

Declare and immediately execute the lambda function is no longer possible. When the lambda function is declared and immediately called, then the return value is the result of executing the lambda function, and not the lambda object's function, which means that it will not be possible to capture the lambda object of the function, so both of the above ways of writing recursive lambda functions are not suitable.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html