diff options
author | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-22 06:00:05 +0000 |
---|---|---|
committer | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-22 06:00:05 +0000 |
commit | 1d91eb52b619c15d0ae927730e464616a08137f2 (patch) | |
tree | 8d1247f34a397da2c1a537c437abd14e8a415d47 /list.cpp | |
parent | 8f0ee1694bfb20b1c07d92c2ef46f516cbfa6f29 (diff) | |
download | algorithms-1d91eb52b619c15d0ae927730e464616a08137f2.tar.gz algorithms-1d91eb52b619c15d0ae927730e464616a08137f2.tar.bz2 algorithms-1d91eb52b619c15d0ae927730e464616a08137f2.zip |
(list)+reduce function
Basically accumulates values, check
https://en.wikipedia.org/wiki/Fold_(higher-order_function) for more
detail.
Diffstat (limited to 'list.cpp')
-rw-r--r-- | list.cpp | 13 |
1 files changed, 13 insertions, 0 deletions
@@ -64,6 +64,18 @@ void map(List<T> *lst, U (*f)(T)) } template <typename T> +T reduce(List<T> *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 <typename T> std::ostream& operator<<(std::ostream& ostream, const List<T> *lst) { if (!lst) @@ -82,6 +94,7 @@ int main(void) std::cout << lst << std::endl; map<int, int>(lst = reverse(lst), [](int x){ return x * 2; }); std::cout << lst << std::endl; + std::cout << reduce<int>(lst, [](int a, int b) { return a + b; }, 0) << std::endl; delete lst; return 0; } |