-
-
Save anonymous/4334155 to your computer and use it in GitHub Desktop.
#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()); | |
} | |
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)?
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).
@jrwest what most people would do is this:
@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
compile with clang++ --std=c++11 maybe.cpp