[Haskell-cafe] Re: Datatypes - Haskell

ajb at spamcop.net ajb at spamcop.net
Sun Feb 10 17:45:22 EST 2008

G'day all.

On Feb 10, 2008 3:40 PM, Mattes Simeon <simeon.mattes at gmail.com> wrote:

>> Though in comparison with C or C++ I can't figure out so clear the syntax.

Quoting Victor Nazarov <asviraspossible at gmail.com>:

> I think this is the most native way to do it in C++:

Herb Sutter and Andrei Alexandrescu will find you and beat you up if
you write this.  This is considered more appropriate.  (Warning: untested
code follows.)

#include <boost/variant.hpp>

template<typename A, typename B>
class Tuple : public boost::variant<A, std::pair<A,B> >
     typedef std::pair<A,B> pair_type;
     typedef boost::variant<A, pair_type> base_type;

     struct visitor_A : public boost::static_visitor<const A*>
         const A* operator()(const A& a) { return &a; }
         const A* operator()(const pair_type& p) { return &p.first; }


     Tuple(const A& a)
         : base_type(a)

     Tuple(const A& a, const B& b)
         : base_type(pair_type(a,b))

     const A* tuple1() const
         return boost::apply_visitor(visitor_A(), *this);

     const B* tuple2() const
         const pair_type* p = boost::get<pair_type>(*this);
         return p ? &p->second : 0;

But in this specific case, this might be more appropriate:

template<typename A,typename B>
class Tuple
     A m_a;
     boost::optional<B> m_b;
     // etc

Andrew Bromage

More information about the Haskell-Cafe mailing list