tags:

views:

430

answers:

3

i am new to c++0x, so please excuse me if my question is silly :).

i am writing the following recursive lambda function, it doesn't compile.

sum.cpp

#include <iostream>
#include <functional>

auto term = [](int a)->int {
  return a*a;
};

auto next = [](int a)->int {
  return ++a;
};

auto sum = [term,next,&sum](int a, int b)mutable ->int {
  if(a>b)
    return 0;
  else
    return term(a) + sum(next(a),b);
};

int main(){
  std::cout<<sum(1,10)<<std::endl;
  return 0;
}

compilation error:

vimal@linux-718q:~/Study/09C++/c++0x/lambda> g++ -std=c++0x sum.cpp

sum.cpp: In lambda function: sum.cpp:18:36: error: ‘((*)this)->::sum’ cannot be used as a function

gcc version

gcc version 4.5.0 20091231 (experimental) (GCC)

but if i change the declaration of sum() as below, it works:

std::function<int(int,int)> sum = [term,next,&sum](int a, int b)->int {
   if(a>b)
     return 0;
   else
     return term(a) + sum(next(a),b);
};

could someone please throw light on this?

Thanks,

+1  A: 

I do not think you can use a recursive lambda function in C++ or Python or most if not all other languages (depends on what they mean by lambda).

Lambda is anonymous function, so how would you call it if it has no name.

Please forgive me for using Python (it is readable) but these are almost equivalent:

def incr(x): return x + 1
incr = lambda x: x+1

Except that function has a name, lambda does not, but it has a named variable pointing to it.

Lambdas are meant to be simple. When you need recursion - use a function.

Hamish Grubijan
thanks for the clarification about lambda and function...in c++0x, what is the type of the named variable, declared as 'auto', which points to a lambda?is it possible to capture that type using decltype()?
weima
Take a look here http://msdn.microsoft.com/en-us/library/6k3ybftz(VS.80).aspx
Hamish Grubijan
A: 

You're trying to capture a variable (sum) you're in the middle of defining. That can't be good.

I don't think truely self-recursive C++0x lambdas are possible. You should be able to capture other lambdas, though.

Terry Mahaffey
but it does work if declaration of sum is changed from 'auto' to std::function<int(int,int)> without changing the capture-list.
weima
Because it is no longer a lambda then, but a function which can be used in place of lambda?
Hamish Grubijan