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

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

A problem with C++ lambdas?

18 February, 201530 June, 2015

C++ lambdas are wonderful for all sorts of reasons (especially with their C++14-and-beyond power). But I’ve run into a problem that I can’t think of a good way around yet. If you’re up to date with C++, of course you know that rvalue references and move semantics are a major…

Read More

How to print anything in C++ (part 1)

1 February, 201530 June, 2015

Part 1 Part 2 Part 3 Part 4 Part 5 Postscript I thought I’d have a go at writing some code that could print things. A pretty-printer, if you like. What I want to be able to do is this: // Print x correctly, where x is ANY type. cout

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