Skip to content

Instantly share code, notes, and snippets.

@dpwright
Created September 6, 2013 15:35
Show Gist options
  • Save dpwright/6465597 to your computer and use it in GitHub Desktop.
Save dpwright/6465597 to your computer and use it in GitHub Desktop.
General Maybe monad in C++
#include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
template<typename a> class Maybe
{
public:
static Maybe<a> Just(a value) { return Maybe(value); }
static Maybe<a> Nothing() { return Maybe(); }
bool isJust() { return m_valid; }
a getJust() { assert(isJust()); return m_value; }
template<typename b> Maybe<b> operator>>=(Maybe<b> (*f)(int)) {
return isJust() ? f(getJust()) : Maybe<b>::Nothing();
}
Maybe<a> unit(a value) { return Maybe(value); }
void show() {
if(isJust())
cout << "Just " << getJust() << endl;
else
cout << "Nothing" << endl;
}
private:
Maybe() : m_value(0), m_valid(false) {}
Maybe(a value) : m_value(value), m_valid(true) {}
a m_value;
bool m_valid;
};
Maybe<int> IM_Square(int a) { return (abs(a) >= 0x8000) ? Maybe<int>::Nothing() : Maybe<int>::Just(a * a); }
int main(int argc, char** argv)
{
Maybe<int> result = Maybe<int>::Nothing();
result = Maybe<int>::Just(0x4000) >>= IM_Square;
result.show();
result = (Maybe<int>::Just(0x4000) >>= IM_Square) >>= IM_Square;
result.show();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment