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