83

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?

Community
  • 1
  • 1
fredoverflow
  • 246,999
  • 92
  • 370
  • 646
  • 1
    possible with huge std::function overhead or with polymorphic lambdas. – ipc Jan 25 '13 at 23:36
  • @MichaelBurr, Great link you have there. – chris Jan 25 '13 at 23:40
  • 2
    Oops - I accidentally deleted my comment. here's the link back: http://blogs.msdn.com/b/vcblog/archive/2008/11/18/stupid-lambda-tricks.aspx – Michael Burr Jan 25 '13 at 23:44
  • @MichaelBurr, It's funny. I find the notion that you accidentally deleted your comment laughable, but I can relate to how easy it is to do something like that :p – chris Jan 25 '13 at 23:46
  • I'm just gonna leave this here http://www.slideshare.net/adankevich/c11-15621074 29 slide – innochenti Jan 29 '13 at 19:06
  • Why not just Y-combinator? http://rosettacode.org/wiki/Y_combinator#C.2B.2B – kerzol Jan 30 '15 at 23:38

1 Answers1

116

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.

Andy Prowl
  • 119,862
  • 22
  • 374
  • 446