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

Exercising Ranges (part 8)

1 July, 20152 July, 2015

(Start at the beginning of the series if you want more context.) Extras from the Haskell Prelude Having implemented iterate, there were a couple of other useful things from the Haskell Prelude that I wanted to have available with ranges. First, there’s cycle. It simply takes a finite range and…

Read More

fighting the code

25 March, 200729 July, 2007

Why doesn’t automake/autoconf properly recognise the way to use Flex/Bison with C++ scanner/parser generation? I use a .ll file and it thinks the output is going to be a .c instead of a .cc. Likewise I use a .yy file and it screws up the includes in my bison output…

Read More

Experimenting with constexpr

13 October, 201515 October, 2015

Since seeing Scott Schurr at C++Now in Aspen and hearing his talks about constexpr, it’s been on my list of things to try out, and recently I got around to it. With the release of Visual Studio 2015, Microsoft’s compiler now finally supports C++11 style constexpr (modulo some minor issues),…

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