2020-03-16 15:11:40 +01:00
|
|
|
#ifndef _functools_H_
|
|
|
|
#define _functools_H_
|
|
|
|
|
|
|
|
#include <vector>
|
|
|
|
#include <functional>
|
|
|
|
#include <algorithm>
|
|
|
|
#include <iterator>
|
|
|
|
|
|
|
|
namespace sc {
|
|
|
|
|
2021-07-26 21:45:13 +02:00
|
|
|
// std::vector versions
|
|
|
|
|
2020-03-16 15:11:40 +01:00
|
|
|
template<class T, class M>
|
|
|
|
std::vector<M> map(const std::vector<T>& seq, std::function<M(T)> fun) {
|
|
|
|
std::vector<M> result;
|
2022-11-01 11:39:09 +01:00
|
|
|
std::transform(seq.begin(), seq.end(), std::back_inserter(result), fun);
|
2020-03-16 15:11:40 +01:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class T>
|
|
|
|
std::vector<T> filter(const std::vector<T>& seq, std::function<bool(T)> fun) {
|
|
|
|
std::vector<T> result;
|
2022-11-01 11:39:09 +01:00
|
|
|
std::copy_if(seq.begin(), seq.end(), std::back_inserter(result), fun);
|
2020-03-16 15:11:40 +01:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class T, class R>
|
|
|
|
R reduce(const std::vector<T>& seq, R seed, std::function<R(T, R)> fun) {
|
|
|
|
R result {seed};
|
|
|
|
for (const auto& elem : seq) {
|
|
|
|
result = fun(elem, result);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2021-07-26 21:45:13 +02:00
|
|
|
// iterator versions
|
|
|
|
|
|
|
|
template<class T, class M, class FwdIter>
|
2021-07-28 14:17:32 +02:00
|
|
|
std::vector<M> map(FwdIter begin, FwdIter end, std::function<M(T)> fun) {
|
2021-07-26 21:45:13 +02:00
|
|
|
std::vector<M> result;
|
|
|
|
std::transform(begin, end, std::back_inserter(result), fun);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class T, class FwdIter>
|
2021-07-28 14:17:32 +02:00
|
|
|
std::vector<T> filter(FwdIter begin, FwdIter end, std::function<bool(T)> fun) {
|
2021-07-26 21:45:13 +02:00
|
|
|
std::vector<T> result;
|
|
|
|
std::copy_if(begin, end, std::back_inserter(result), fun);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class T, class R, class FwdIter>
|
2021-07-28 14:17:32 +02:00
|
|
|
R reduce(FwdIter begin, FwdIter end, R seed, std::function<R(T, R)> fun) {
|
2021-07-26 21:45:13 +02:00
|
|
|
R result {seed};
|
|
|
|
for (FwdIter it = begin; it != end; ++it) {
|
|
|
|
result = fun(*it, result);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2020-03-16 15:11:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#endif // _functools_H_
|