1

I'm trying to define a recursive lambda.

In other languages, such as go, it could be declared as:

func main() {
    var f func()
    f = func() { f() }
}

Maybe it's caused by implementation with template?

#include <functional>

int main() {
  std::function<int()> f;
  int a = 0;
  f = [f,&a]() -> int {
    a++;
    if (a > 2) {
      return 1;
    }
    return f();
  };
  if (f() != 0) {
    goto out;
  }

  out:
  return 0;
}

Here's my compiler:

Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
4
  • 3
    When posting question about build errors, always include the actual errors you get, in full and complete and copy-pasted as text. Commented Jul 27, 2019 at 13:23
  • 2
    By the way, are you sure you want to capture f by value? Before it's initialized? Commented Jul 27, 2019 at 13:23
  • 1
    I downvoted because the exact text of the compile error needs to be in the question to make this a good question. If it is added I will remove my downvote. Commented Jul 27, 2019 at 13:31
  • 3
    And don't use goto. Especially if it's totally useless (like in the code shown). Commented Jul 27, 2019 at 13:33

2 Answers 2

4

You are capturing f by value. You want to capture it by reference for a recursive lambda. Here's an example recursive lambda:

#include <functional>
#include <iostream>

int main() {
    std::function<int(int)> factorial;

    factorial = [&factorial](int i) {
        if (i < 2) {
            return 1;
        }
        return i * factorial(i - 1);
    };
    std::cout << "5! = " << factorial(5) << '\n';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Please don't create examples using goto, not even if the OP have it in their code. The goto statement is almost never a good idea.
@Someprogrammerdude thanks for the feedback. Removed OP's code and added an example without the use of goto
2

std::function is fine in most situations, but if your recursive lambda turns out to be a performance bottleneck, then you can pass the lambda into itself, with an extra argument:

int a = 0;
auto f = [&a](auto&& go) -> int { //explicit return type is required here
  ++a;
  if (a > 2) { return 1; }
  return i * go(go);
};
f(f);

Note that auto in a lambda argument, which is needed to pass a lambda to a lambda, requires at least C++14.

1 Comment

That is neat :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.