Created
September 6, 2013 15:35
Revisions
-
dpwright created this gist
Sep 6, 2013 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ #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; }