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