Lambda functions – recursion and other tricks

A few useful lambda function ideas, especially how to write a recursive lambda function in C++11:

Interestingly, lambdas can be recursive. For example, here’s a lambda that implements the fibonacci series using recursion:

function<int(int)> fib1 = [&fib1](int n) -> int
{
  if(n <= 2)
    return 1;
  else
    return fib1(n-1) + fib1(n-2);
}

Note that we had to actually name the lambda in order to implement the recursion. Without a name, how would you make the recursive call? This self-referencing places some restrictions on how a recursive lambda can be used; the lambda doesn’t refer to itself, it refers to fib1, which happens to be itself.

Leave a comment

Filed under C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.