I am trying to implement the Maybe monad from Haskell using the lambda functions in C++11 and templates. Here\'s what I have so far
#include
#i
Noticed that std::function
have an empty state, we can have the following implementation
template
class Maybe{
private:
Maybe(T t){
get = [t](){ return t; };
}
Maybe(){}
std::function get;
public:
typedef T content_type;
template
auto on(WhenJust &&whenJust, WhenNothing &&whenNothing)
-> decltype(whenNothing()){
if(get==nullptr) return whenNothing();
else return whenJust(get());
}
template
friend Maybe just(U u);
template
friend Maybe nothing();
};
template
Maybe just(T t){
return Maybe(t);
}
template
Maybe nothing(){
return Maybe();
}
template
auto operator >>(Maybe m, BinderFunction bind)
-> Maybe {
return m.on([bind](T v){
return bind(v);
},[](){
return nothing();
});
}
In this implementation, all factory methods are free (friend) functions, the >>
operator (not to be confused with >>
in Haskell, this is the equivalent of >>=
with same associative) is also free, and even not a friend function. Also notice the on
member function, this is used to force any client intended to use a Maybe
instance must be prepared for both cases (Just or Nothing).
Here is an example of usage:
int main()
{
auto n = just(10) >> [](int j){ std::cout<> "; return just(j+10.5); }
>> [](double d){ std::cout<> "; return nothing(); }
>> [](char c){ std::cout<
The output is
10 >> 20.5 >> nothing!