(list)+reduce function
Basically accumulates values, check https://en.wikipedia.org/wiki/Fold_(higher-order_function) for more detail.
This commit is contained in:
13
list.cpp
13
list.cpp
@@ -63,6 +63,18 @@ void map(List<T> *lst, U (*f)(T))
|
|||||||
map(lst->next, f);
|
map(lst->next, f);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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>
|
template <typename T>
|
||||||
std::ostream& operator<<(std::ostream& ostream, const List<T> *lst)
|
std::ostream& operator<<(std::ostream& ostream, const List<T> *lst)
|
||||||
{
|
{
|
||||||
@@ -82,6 +94,7 @@ int main(void)
|
|||||||
std::cout << lst << std::endl;
|
std::cout << lst << std::endl;
|
||||||
map<int, int>(lst = reverse(lst), [](int x){ return x * 2; });
|
map<int, int>(lst = reverse(lst), [](int x){ return x * 2; });
|
||||||
std::cout << lst << std::endl;
|
std::cout << lst << std::endl;
|
||||||
|
std::cout << reduce<int>(lst, [](int a, int b) { return a + b; }, 0) << std::endl;
|
||||||
delete lst;
|
delete lst;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user