public
Created

C++11 non-lazy monad

  • Download Gist
eager_monad.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <boost/optional.hpp>
#include <utility>
#include <string>
#include <cassert>
 
template <class T>
struct maybe
{
maybe() {}
maybe(T x) : value(std::move(x)) {}
explicit operator T() const { return value; }
boost::optional<T> value;
};
 
template <class T, class F>
auto operator>>(maybe<T> x, F f) -> maybe<decltype(f(*x.value))>
{
return x.value ? f(*x.value) : maybe<decltype(f(*x.value))>();
}
 
maybe<int> f(int x) { return x < 0 ? maybe<int>() : x; }
std::string xes(unsigned int n) { return std::string(n, 'x'); }
unsigned length(std::string const& s) { return s.size(); }
 
int main()
{
assert(*(f(10) >> xes >> length).value == 10);
assert(!(f(-10) >> xes >> length).value);
assert(!(f(-10) >> xes).value);
assert(!f(-10).value);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.