Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
C++11 non-lazy monad
#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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.