Created
March 10, 2013 22:09
-
-
Save jdeng/5130721 to your computer and use it in GitHub Desktop.
simple map reduce with C++ 11. The sample maps an integer to a string, and reduces with reverse concatenation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <functional> | |
#include <iostream> | |
template <typename R, typename T, typename M> | |
auto map_reduce(const std::vector<T>& input, std::function<M(const T&)> mapper, std::function<R(const M& m, const R& r)> reducer, const R& init) -> decltype(reducer(std::declval<const M&>(), std::declval<const R&>())) | |
{ | |
R r = init; | |
for (auto const & i: input) r = reducer(mapper(i), r); | |
return r; | |
}; | |
int main() | |
{ | |
std::vector<int> input({1, 2, 3, 4, 5, 6}); | |
std::string x = map_reduce<std::string, int, std::string>(input, | |
[](const int& i) { return std::to_string(i); }, | |
[](const std::string& b, const std::string& r) { return r.empty()? b: b + "," + r; }, | |
"" | |
); | |
std::cout << x << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment