I used lambda expression a lot in C#, but never tried it in C++. Lambda is a part of new C++ standard, i.e. C++11. Today I tried to give a try of lambda in C++ and play with it little bit. I used Microsoft Visual C++ 2010 which has a lambda support. To make things even more interesting, I tried to do recursion with lambda function. I already wrote “Recursion Primer using C++” series here, here and here, so getting examples is not a difficult part.
By definition lambda method doesn’t have any name and we need a function name to call it recursively. These are very opposite concepts. But to overcome this situation we can use the function pointer to store the lambda expression and call function recursively using function pointer. C++ TR1 introduced a wrapper class named function “std::tr1::function” define in functional class. Let’s start with our simple and typical factorial program. Here is lambda recursive version of factorial function.
We can even call the recursive function twice. Here is an example of binary recursion.
Calling nested function is also very similar. Here is an example of nested recursion.
In a same way if we want to pass more than one parameter to the recursive function we can do it easily. Here is a recursive function to reverse the number.