Skip to content

Instantly share code, notes, and snippets.

@dpwright
Created September 6, 2013 15:35

Revisions

  1. dpwright created this gist Sep 6, 2013.
    49 changes: 49 additions & 0 deletions maybem.cpp
    Original 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;
    }