diff options
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; } |