Created
December 30, 2011 18:33
-
-
Save dabrahams/1540941 to your computer and use it in GitHub Desktop.
C++11 non-lazy monad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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> const& x, F f) -> decltype(f(*x.value)) | |
{ | |
return x.value ? f(*x.value) : decltype(f(*x.value))(); | |
} | |
maybe<int> f(int x) { return x < 0 ? maybe<int>() : x; } | |
maybe<std::string> xes(unsigned int n) { return std::string(n, 'x'); } | |
maybe<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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment