Lambda to compose lambdas



我试着用c++写一个函数,它可以组成一个可变数量的lambdas。我的第一次尝试有点效果(尽管我怀疑它并不完美)

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不能捕获自己。这使得"lambdafing"变得简单。我的模板函数有问题。有没有人有一个替代的方法或想法如何获得类似的结果与lambda函数?

您可以使用y组合子来创建递归lambda

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);
}
});

现场观看

最新更新