I repeatedly find myself requiring Haskell style Maybe (especially Maybe chaining) in my project at work. E.g. withdrawal request from customer and we are given the customer ID... lookup customer in cache... if customer is found... lookup her savings account... if there is an account... withdraw... At any point in this chain, if there is a lookup failure, do nothing and return a failure.
My chains are large... sometimes as long as 6... so here is my swipe at Haskell.Data.Maybe in C++0x... (note... this should work in C++ if I stop using variadic templates). I have worked out chaining for free-functions taking one argument or member functions taking no arguments and I am happy with the interface. However, for functions taking multiple parameters... I have to write a lambda function to simulate partial application. Is there a way to avoid it? See the last line of main(). Even if it is uncommented it won't compile, but for const/non-const mixing. But the question still stands.
Sorry about the large chunk of code... I hope this wouldn't turn away people who might otherwise be interested in this...
#include <iostream>
#include <map>
#include <deque>
#include <algorithm>
#include <type_traits>
typedef long long int int64;
namespace monad { namespace maybe {
struct Nothing {};
template < typename T >
struct Maybe {
template < typename U, typename Enable = void >
struct ValueType {
typedef U * const type;
};
template < typename U >
struct ValueType < U, typename std::enable_if < std::is_reference < U >::value >::type > {
typedef typename std::remove_reference < T >::type * const type;
};
typedef typename ValueType < T >::type value_type;
value_type m_v;
Maybe(Nothing const &) : m_v(0) {}
struct Just {
value_type m_v;
Just()