Boost logo

Boost :

Subject: Re: [boost] Interest in an 'either' library?
From: Eric Niebler (eniebler_at_[hidden])
Date: 2013-06-24 12:31:58


On 6/21/2013 9:35 AM, David Sankel wrote:
> **semantics**:
>
> template< typename left_type, typename right_type>
> struct either
> {
> // postcondition, is_left()
> either( left_type );
>
> // postcondition, is_right()
> either( right_type );
>
> bool is_left() const;
> bool is_right() const;
>
> // postcondition, is_left()
> either & operator=( left_type );
>
> // postcondition, is_right()
> either & operator=( right_type );
>
> // precondition, is_left()
> left_type left();
>
> // precondition, is_right()
> right_type right();
> private:
> };
>
> **uses**:
>
> **Use 1**: Can be used as an alternative to exceptions or the (error
> codes+set reference idiom):
>
> either<error_code, file_id> load_file(...);
>
> vs.
>
> error_code load_file( file_id &, ... );
>
> or
>
> // throws std::exception
> file_id load_file(...);
>
> **Use 2**: A lightweight alternative to boost::variant when only 2
> components are required (either relates to variant in a similar way that
> pair relates to tuple ).
>
> variant<A,B> eitherAOrB;
> if( A * aPtr = boost::get<A>( &eitherAOrB ) )
> std::cout << "A: " << *aPtr;
> else
> std::cout << "B: " << boost::get<B>( eitherAOrB );
>
> vs.
>
> either<A,B> eitherAOrB;
>
> if( eitherAOrB.is_left() )
> std::cout << "A: " << eitherAOrB.left();
> else
> std::cout << "B: " << eitherAOrB.right();

This misses what is, IMO, the most important use case of Haskell's
Either monad: automatic error propagation. This would be more useful if
there were a way to call a function such that if any of the function's
arguments were an Either-in-error, the function would immediately return
the error.

I implemented something like this. Check out substitution_failure and
try_call starting here:

https://github.com/ericniebler/proto-0x/blob/master/boost/proto/v5/utility.hpp#L742

-- 
Eric Niebler
Boost.org
http://www.boost.org

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