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

C++11 compile-time string hashing

13 October, 201515 October, 2015

(Start at the beginning of the series – and all the source can be found in my github repo) Now that I was used to writing C++11-style constexpr, I decided to try some compile-time string hashing. It turns out that FNV1 is very easy to express in a move-down-the-string recursive…

Read More

“Smart and Gets Things Done”?

29 January, 200828 February, 2008

I work for a big games company as a senior programmer, and I’m a regular on the interview loop. While I’d love to hire candidates who are smart and get things done, the reality of the situation is that more often than not I also have to hire candidates with…

Read More

Atomic brain to power, fingers to speed…

17 February, 200529 July, 2007

I’m not a touch typer, but I am a pretty fast (8-finger or so) typer after 20 years of keyboarding, and I don’t actually have to look at the keys much. Of course, most of the kind of typing that I do is quite different from actual written English –…

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