45 lines
945 B
C++
45 lines
945 B
C++
//
|
|
// functools.hpp
|
|
// libcommon
|
|
//
|
|
// Created by Bob Polis at 2019-10-19
|
|
// Copyright (c) 2019 SwiftCoder. All rights reserved.
|
|
//
|
|
|
|
#ifndef _functools_H_
|
|
#define _functools_H_
|
|
|
|
#include <vector>
|
|
#include <functional>
|
|
#include <algorithm>
|
|
#include <iterator>
|
|
|
|
namespace sc {
|
|
|
|
template<class T, class M>
|
|
std::vector<M> map(const std::vector<T>& seq, std::function<M(T)> fun) {
|
|
std::vector<M> result;
|
|
std::transform(seq.begin(), seq.end(), back_inserter(result), fun);
|
|
return result;
|
|
}
|
|
|
|
template<class T>
|
|
std::vector<T> filter(const std::vector<T>& seq, std::function<bool(T)> fun) {
|
|
std::vector<T> result;
|
|
std::copy_if(seq.begin(), seq.end(), back_inserter(result), fun);
|
|
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;
|
|
}
|
|
|
|
}
|
|
|
|
#endif // _functools_H_
|