首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Lambda将组成Lambda

Lambda将组成Lambda
EN

Stack Overflow用户
提问于 2021-09-17 08:19:16
回答 1查看 84关注 0票数 0

我试着用C++写了一个函数,它可以组成可变数量的lambda。我的第一次尝试是可行的(尽管我怀疑它并不完美)。

代码语言:javascript
复制
template <typename F, typename G> auto compose(F f, G g) {
  return
      [f, g](auto &&...xs) { return g(f(std::forward<decltype(xs)>(xs)...)); };
}

template <typename F, typename G, typename... Fs>
auto pipe(F f, G g, Fs... fs) {
  if constexpr (sizeof...(fs) > 0) {
    auto fg = compose(f, g);
    return pipe(fg, fs...);
  } else {
    return compose(f, g);
  }
}

int main() {

  auto add_x = [](const auto &x) {
    return [x](auto y) {
      std::cout << "+" << x << std::endl;
      return y + x;
    };
  };

  auto to_str = [](const auto &s) {
    std::cout << "to_str" << std::endl;
    return std::string("String:") + std::to_string(s);
  };

  auto add_1 = add_x(1);
  auto add_2 = add_x(2);
  auto add_3 = add_x(3);

  auto piped = pipe(add_1, add_2, add_3, to_str);

  auto x = piped(3);

  std::cout << x << std::endl;
}

但是,我希望pipe函数本身成为一个lambda函数。然而,这有点难,因为据我所知,lambda不能捕获自己。这使得简单地"lambdafying“我的模板函数成了问题。有没有人有替代方法或想法如何用lambda函数得到类似的结果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-17 08:36:58

您可以使用y组合器来创建一个递归lambda。

代码语言:javascript
复制
template<class Fun>
class y_combinator_result {
    Fun fun_;
public:
    template<class T>
    explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {}

    template<class ...Args>
    decltype(auto) operator()(Args &&...args) {
        return fun_(std::ref(*this), std::forward<Args>(args)...);
    }
};

template<class Fun>
decltype(auto) y_combinator(Fun &&fun) {
    return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}

template <typename F, typename G> auto compose(F f, G g) {
  return
      [f, g](auto &&...xs) { return g(f(std::forward<decltype(xs)>(xs)...)); };
}

auto pipe = y_combinator([](auto self, auto f, auto g, auto... fs){
  if constexpr (sizeof...(fs) > 0) {
    auto fg = compose(f, g);
    return self(fg, fs...);
  } else {
    return compose(f, g);
  }
});

See it live

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69220040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档