Boost logo

Boost :

Subject: [boost] [Optional] Monadic bind
From: Tobias Loew (Tobias.Loew_at_[hidden])
Date: 2015-06-22 09:49:47


While playing around with boost::optionals I had code like the following

struct A {
...
int i;
...
};

boost::optional a;
// do something with 'a'

// optional-projection to a::i
boost::optional<int> a_i;
if(a)
    a_i = a->i;

which seemed quite verbose for something that's rather natural in functional
languages: boost::optional is a monadic structure, which lifts a type T by
extending it with a new bottom-element (represented by the empty
optional<T>), thus it should also have a "bind" and a "map"-equivalent,
which could be implemented for instance as as member functions of optional

template<class B>
auto bind(B&& binder) const
    -> boost::optional<typename std::decay<decltype(std::bind(binder,
get())())>::type>
{
    if(this->is_initialized())
    {
        return std::bind(binder, get())();
    }
    else
    {
        return boost::none;
    }
}

and

template<class B>
auto map(B&& f) const
    -> boost::optional<typename std::decay<decltype(std::bind(f,
get())())>::type>
{
    if(this->is_initialized())
    {
        return std::bind(f, get())();
    }
    else
    {
        return boost::none;
    }
}

where map lifts f from A->B to optional -> optional< B > and applies 'this'
to it.
This would allow things like

boost::optional a;
auto a_i = a.map(&A::i); // "optional-projection"; type of a_i is
boost::optional<int>

Tobias

--
View this message in context: http://boost.2283326.n4.nabble.com/Optional-Monadic-bind-tp4677431.html
Sent from the Boost - Dev mailing list archive at Nabble.com.

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk