Created
December 19, 2012 03:29
-
-
Save anonymous/4334155 to your computer and use it in GitHub Desktop.
maybe derp
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 characters
| #include <cstdio> | |
| #include <stdexcept> | |
| template <class T> | |
| struct Maybe { | |
| Maybe( const T& val ) : val_(val), valid_(true) { } | |
| Maybe() : valid_(false) { } | |
| const T& get() const { | |
| if (valid_) return val_; | |
| throw std::logic_error("lol type systems"); | |
| } | |
| private: | |
| T val_; | |
| bool valid_; | |
| }; | |
| template <class T> | |
| Maybe<T> Just(const T& val) { | |
| return Maybe<T>(val); | |
| } | |
| template <class T> | |
| Maybe<T> Nothing() { | |
| return Maybe<T>(); | |
| } | |
| Maybe<int> isYouPositive(int x) | |
| { | |
| if (x > 0) return Just(x); | |
| return Nothing<int>(); | |
| } | |
| int main(void) | |
| { | |
| auto a = isYouPositive(1); | |
| printf("%d\n", a.get()); | |
| auto b = isYouPositive(-1); | |
| printf("%d\n", b.get()); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@argv0 cool! In that case its actually more accurate than the Scala stdlib impl in that Just/Nothing should only be constructors not types. Of course its possible to do so in Scala (note: this is Maybe monad transformer, not just Maybe): https://gist.github.com/943f6fba5cf6f8f31a9f