Skip to content
Why is a raven like a writing desk?

Thoughts both confusing and enlightening.

Why is a raven like a writing desk?

Thoughts both confusing and enlightening.

Recursive lambdas

elbeno, 16 April, 201530 June, 2015

One can assign a lambda to auto or to std::function. Normally one would assign a lambda to auto to avoid possible unwanted allocation from std::function. But if you want recursion, you need to be able to refer to the lambda variable inside the lambda, and you can’t do that if it’s assigned to auto. So how do you do recursive lambdas without using std::function?

Use a fixed-point combinator (y-combinator) of course.

#include 
#include 

template
struct Fix
{
  Fix(const F& f)
    : m_f(f)
  {}

  Fix(F&& f)
    : m_f(std::move(f))
  {}

  template 
  auto operator()(T t) const
  {
    return m_f(*this, t);
  }

  F m_f;
};

template
auto fix(F&& f)
{
  return Fix(std::forward(f));
}

int main(void)
{
  auto f = fix(
      [] (auto& f, int x) -> int
      {
        if (x <= 2) return 1;
        return f(x-1) + f(x-2);
      });
  std::cout << f(6) << std::endl;

  return 0;
}

This code compiles with GCC 4.9.1, Clang 3.4.2 or MSVC 2015 preview (and produces "8" as the output). Clang allows omission of the lambda's trailing return type.

C++ Programming

Post navigation

Previous post
Next post

Related Posts

A Crossword for CppCon 2024

12 September, 202411 September, 2024

As well as being a C++ enthusiast, I’m a bit of a cruciverbalist. I do the Guardian cryptic every day (not in a particularly competitive time — I’d count sub-20 minutes as a good day), and sometimes others when I can. Like many Brits, I learned to do cryptic crosswords…

Read More

a nightmare

20 March, 200629 July, 2007

Last night I dreamt that the IT guys at work took my home PC and “upgraded” it with Windows Vista. They didn’t seem to understand that I don’t use Windows – my remonstrations fell on deaf ears. In other news, I spent the weekend playing with fractals. When fractals were…

Read More

RotateAVI v0.91beta

8 January, 200729 July, 2007

It’s up on elbeno.com. If you got a digital camera for Xmas (or otherwise), check it out. An easy way to rotate avi movies.

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *

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

©2026 Why is a raven like a writing desk? | WordPress Theme by SuperbThemes