I write some scala at home for fun that night and thought: “Would it be great if we had such an API in C ++?” Is it possible? ". I started looking for C ++, monads, and stl collections, but I couldn’t find anything that seemed to increase my productivity: /.
So, I decided to implement some proof of the concept (super inefficient, but at least it works! :)), which is usually observed in more specialized functional languages.
auto m = monadic(std::vector<int>{1,2,3}); auto mMapped = m.map([](int x) {return x*x; }); Monadic<std::vector<int>> mFiltered = m.filter([](int x) {return x > 1; }); std::vector<std::string> funList = monadic(src) .flatMap([](int x) { return std::vector<int>{1,2,3};} ) .filter([](int x) { return x > 1; }) .map([](int x) { return std::to_string(x).append("_string"); }) .col;
I would really like such a library (but more complete and efficient using move semantics) for my daily C ++ code (data management, threads, and distributed execution are becoming so easy).
Question: -> Do you know about any such library for C ++ 11 or C ++ 14? <-
The above code used a very quickly hacked PoC library, which I posted here https://github.com/GiGurra/cpp_monad (Tested with gcc 4.9.2, VS2015 and some version of clang, I don’t remember).
The "Monadic" class does not contain any specific implementation, it just goes over to the fact that the available map / filter / flatMap functions are available for this type of collection, for example, the map operation is very naively implemented, for example:
class Monadic { public: ... template <typename MapFcn> auto map(MapFcn mapFcn) { return monadic(cpp_monad::map(col, mapFcn)); } ... }; // Default naive implementation in unspecialized case template <typename T_Coll, typename T_MapFcn> auto map(const T_Coll& src, T_MapFcn fcn) { std::vector<decltype(fcn(internal::_firstElem(src)))> out; std::transform(std::begin(src), std::end(src), std::back_inserter(out), fcn); return out; };
Thus, you can replace either the shell or the implementation without having to change the code using a specific API.
Just an idea, maybe something is already there, but much better.