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 give
I was the OP (lost my account when SO migrated). Here is the latest I came up with using std::invoke
. Life becomes much simpler
template < typename T >
auto operator | (Maybe < T > const & v, auto && f)
{
using U = std::decay_t < decltype(f(v.get())) >;
if (v.isNull())
return Maybe < U >::nothing();
else
return Maybe < U >::just(std::invoke(f, v.get()));
}
template < typename T >
auto operator | (Maybe < T > & v, auto && f)
{
using U = std::decay_t < decltype(f(v.get())) >;
if (v.isNull())
return Maybe < U >::nothing();
else
return Maybe < U >::just(std::invoke(f, v.get()));
}
template < typename T >
auto operator | (Maybe < T > && v, auto && f)
{
using U = std::decay_t < decltype(f(v.get())) >;
if (v.isNull())
return Maybe < U >::nothing();
else
return Maybe < U >::just(std::invoke(f, v.get()));
}