fork(2) download
  1. #include <iostream>
  2. #include <functional>
  3. #include <vector>
  4. #include <iterator>
  5. using namespace std;
  6.  
  7. template <template <class...> class>
  8. struct monad;
  9. template <template <class...> class M, typename A, typename F>
  10. auto operator >>=(M<A> const & x, F f) -> decltype(declval<F>()(declval<A>())) {
  11. return monad<M>::bind(x, f);
  12. };
  13. template <template <class...> class M, typename T>
  14. auto return_(T x) -> M<T> {
  15. return monad<M>::return_(x);
  16. }
  17.  
  18. template <>
  19. struct monad<vector> {
  20. template <typename A, typename F>
  21. static auto bind(vector<A> const & x, F f) -> decltype(declval<F>()(declval<A>())) {
  22. typedef decltype(declval<F>()(declval<A>())) vector_B;
  23. vector_B ret;
  24. for (typename vector<A>::const_iterator it = x.begin(), iend = x.end(); it != iend; ++it) {
  25. vector_B r = f(*it);
  26. copy(r.begin(), r.end(), back_inserter(ret));
  27. }
  28. return ret;
  29. }
  30. template <typename T>
  31. static auto return_(T x) -> vector<T> {
  32. return vector<T>(1, x);
  33. }
  34. };
  35.  
  36. int main() {
  37. vector<int> v = {1, 2, 3}, w = {1, 2, 3};
  38. vector<int> r = v >>= [&](int x) { return w >>= [&](int y) { return return_<vector, int>(x+y); }; };
  39. copy(r.begin(), r.end(), ostream_iterator<int>(cout, " "));
  40. }
Success #stdin #stdout 0s 3060KB
stdin
Standard input is empty
stdout
2 3 4 3 4 5 4 5 6