aboutsummaryrefslogtreecommitdiff
path: root/list.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'list.cpp')
-rw-r--r--list.cpp13
1 files changed, 13 insertions, 0 deletions
diff --git a/list.cpp b/list.cpp
index e95a0ac..b83b018 100644
--- a/list.cpp
+++ b/list.cpp
@@ -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;
}