Skip to content

Instantly share code, notes, and snippets.

Created December 19, 2012 03:29
Show Gist options
  • Save anonymous/4334155 to your computer and use it in GitHub Desktop.
Save anonymous/4334155 to your computer and use it in GitHub Desktop.
maybe derp
#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());
}
@argv0
Copy link

argv0 commented Dec 19, 2012

compile with clang++ --std=c++11 maybe.cpp

@jrwest
Copy link

jrwest commented Dec 19, 2012

given my c++ skills are totally lacking, am I correct in understanding that Just/Nothing are simply functions that return type Maybe<T> or are they themselves types (its the template keyword above them im not sure about)?

@argv0
Copy link

argv0 commented Dec 19, 2012

they are just functions that return a Maybe of T, where T is the type of their argument- so it'd work for primitive types or any user defined types, provided they both 1) a default, 0-arg constructor (implicitly required in line 7) or a constructor taking a const reference to T (required in line 6).

@argv0
Copy link

argv0 commented Dec 19, 2012

@jrwest what most people would do is this:

https://gist.github.com/4335050

@jrwest
Copy link

jrwest commented Dec 19, 2012

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment