Advertisement
Guest User

Untitled

a guest
May 26th, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <vector>
  3.  
  4. template<typename A> struct maybe {
  5.   bool nothing;
  6.   A data;
  7.   maybe(A a) : data(a), nothing(false) { }
  8.   maybe() : nothing(true) { }
  9.   template<typename B> maybe<B> bind (maybe<B> (f)(A)) {
  10.     if (nothing) {
  11.       return maybe();
  12.     } else {
  13.       return maybe(f(data));
  14.     }
  15.   }
  16. };
  17.  
  18. template<typename A> struct list: std::vector<A> {
  19.   list () : std::vector<A>() { }
  20.   template<int len> list (const A (&a)[len]) : std::vector<A>(a, a + len) { }
  21.   template<typename B> list<B> bind (list<B> (f)(A)) {
  22.     list<B> out;
  23.     for (auto& i : *this) {
  24.       list<B> temp = f(i);
  25.       out.insert(out.end(), temp.begin(), temp.end());
  26.     }
  27.     return out;
  28.   }
  29. };
  30.  
  31. maybe<int> mprint (int i)
  32. {
  33.   printf("%i\n", i);
  34.   return maybe<int>(i);
  35. }
  36.  
  37. list<int> lprint (int i)
  38. {
  39.   printf("%i\n", i);
  40.   return list<int>((int[]){i});
  41. }
  42.  
  43. int main ()
  44. {
  45.   maybe<int> x;
  46.   maybe<int> y = 23;
  47.   x.bind(mprint);
  48.   y.bind(mprint);
  49.   list<int> z = (int[]){1, 2, 3};
  50.   z.bind(lprint);
  51.   return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement