From 25cd6e9eed5834db9028be85b0fe9b00c699495c Mon Sep 17 00:00:00 2001 From: sha512sum Date: Fri, 12 Apr 2024 12:16:37 +0000 Subject: [PATCH] Add reduce --- examples/src/pipe.cpp | 16 ++++++++++++---- include/utempl/utils.hpp | 11 +++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/examples/src/pipe.cpp b/examples/src/pipe.cpp index bfc01ee..00b2bb9 100644 --- a/examples/src/pipe.cpp +++ b/examples/src/pipe.cpp @@ -1,12 +1,20 @@ #include +struct Container { + float data{}; +}; + auto main() -> int { using namespace utempl; - constexpr TupleLike auto tuple = Tuple{1, 2, 3, 4, 5, 6} + constexpr auto value = Tuple{1, 2, 3, 4, 5, 6} | Take<5>() - | Map([](int arg){return arg + 1;}) + | Map([](int arg) {return arg + 1;}) | Map([](int arg) -> float {return arg;}) + | Map([](float arg) -> Container {return {.data = arg};}) | Reverse() - | Take<3>(); // Lazy evaluate - static_assert(tuple == Tuple{6.0f, 5.0f, 4.0f}); + | Take<3>() + | Reduce(0.f, [](auto accumulator, Container arg) -> float { + return accumulator + arg.data; + }); // Lazy evavalue + static_assert(value == 15.0f); }; diff --git a/include/utempl/utils.hpp b/include/utempl/utils.hpp index 07c0976..04441f5 100644 --- a/include/utempl/utils.hpp +++ b/include/utempl/utils.hpp @@ -389,6 +389,17 @@ inline constexpr auto LeftFold(Tuple&& tuple, T&& init, F&& f) { }); }; +template +inline constexpr auto Reduce(Tuple&& tuple, T&& init, F&& f) { + return LeftFold(std::forward(tuple), std::forward(init), std::forward(f)); +}; + +template +inline constexpr auto Reduce(T&& init, F&& f) { + return [init = std::forward(init), f = std::forward(f)](Tuple&& tuple){ + return Reduce(std::forward(tuple), std::move(init), std::move(f)); + }; +}; template