Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Last active May 24, 2020 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TheSeamau5/ef911f50dd5690863bf4 to your computer and use it in GitHub Desktop.
Save TheSeamau5/ef911f50dd5690863bf4 to your computer and use it in GitHub Desktop.
Maybe in C++
#include <string>
#include <functional>
using namespace std;
template <typename T>
struct Maybe{
T just;
bool isNothing;
};
template <typename T>
Maybe<T>* makeMaybe(T just, bool isNothing){
Maybe<T>* maybe = (struct Maybe<T>*) malloc (sizeof(struct Maybe<T>));
maybe->just = just;
maybe->isNothing = isNothing;
return maybe;
}
template <typename T>
Maybe<T>* Just(T just){
return makeMaybe(just, false);
}
template <typename T>
Maybe<T>* Nothing(){
return makeMaybe((T) 0, true);
}
template <typename T>
bool isNothing(Maybe<T>* maybe){
return maybe == NULL || maybe->isNothing;
}
template <typename T>
string toString(Maybe<T>* maybe){
return isNothing(maybe) ? "Nothing" : "Just " + to_string(maybe->just);
}
template <typename A, typename B>
Maybe<B>* map (function<B(A)> f, Maybe<A>* maybe){
return isNothing(maybe) ? Nothing<B>() : Just(f(maybe->just));
}
template <typename A, typename B>
Maybe<B>* operator >>= (Maybe<A>* maybe, function<Maybe<B>*(A)> f){
return isNothing(maybe) ? Nothing<B>() : f(maybe->just);
}
@TheSeamau5
Copy link
Author

Compare with equivalent in Elm:

type Maybe a = Nothing | Just a

map : (a -> b) -> Maybe a -> Maybe b
map f maybe =
  case maybe of
    Nothing -> Nothing
    Just x  -> Just (f x)


(>>=) : Maybe a -> (a -> Maybe b) -> Maybe b
(>>=) maybe f =
  case maybe of
    Nothing -> Nothing
    Just x  -> f x

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