From 1d91eb52b619c15d0ae927730e464616a08137f2 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Mon, 22 Nov 2021 06:00:05 +0000 Subject: (list)+reduce function Basically accumulates values, check https://en.wikipedia.org/wiki/Fold_(higher-order_function) for more detail. --- list.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'list.cpp') diff --git a/list.cpp b/list.cpp index e95a0ac..b83b018 100644 --- a/list.cpp +++ b/list.cpp @@ -63,6 +63,18 @@ void map(List *lst, U (*f)(T)) map(lst->next, f); } +template +T reduce(List *lst, T (*reducer) (T, T), T init = 0) +{ + if (!lst) + return init; + if (!init) + init = lst->value; + else + init = reducer(init, lst->value); + return reduce(lst->next, reducer, init); +} + template std::ostream& operator<<(std::ostream& ostream, const List *lst) { @@ -82,6 +94,7 @@ int main(void) std::cout << lst << std::endl; map(lst = reverse(lst), [](int x){ return x * 2; }); std::cout << lst << std::endl; + std::cout << reduce(lst, [](int a, int b) { return a + b; }, 0) << std::endl; delete lst; return 0; } -- cgit v1.2.3-13-gbd6f