Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can lambda functions be recursive? [duplicate]

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 <= 1) ? 1 : n * operator()(n - 1); } // error: operator() not defined  [](int n) { return (n <= 1) ? 1 : n * (*this)(n - 1); } // error: this wasn't captured for this lambda function 

Is there any expression that denotes the current lambda so it can call itself recursively?

like image 500
fredoverflow Avatar asked Jan 25 '13 23:01

fredoverflow


People also ask

Can a lambda function be recursive?

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.

Can lambda function be called recursively in Python?

It can be written as a recursive functions as explained below.

How do you write a recursive lambda?

Make the LAMBDA function call itself recursively As with any custom Lambda, you start with declaring the parameters: =LAMBDA(data, chars, Next, you evaluate a certain condition and depending on the result either invoke the recursion or exit.

Can lambdas be templated?

From the various lambda improvements, template parameters for lambdas are my favorite ones. Lambdas support with C++20 template parameters, can be default-constructed and support copy-assignment, when they have no state, and can be used in unevaluated contexts.


1 Answers

Yes, they can. You can store it in a variable and reference that variable (although you cannot declare the type of that variable as auto, you would have to use an std::function object instead). For instance:

std::function<int (int)> factorial = [&] (int i)  {      return (i == 1) ? 1 : i * factorial(i - 1);  }; 

Otherwise, no, you cannot refer the this pointer from inside the body of the lambda.

like image 60
Andy Prowl Avatar answered Sep 22 '22 03:09

Andy Prowl