Can C++ do something like an ML case expression?

Posted by Nathan Andrew Mullenax on Stack Overflow See other posts from Stack Overflow or by Nathan Andrew Mullenax
Published on 2012-08-30T20:39:39Z Indexed on 2012/09/01 3:38 UTC
Read the original article Hit count: 241

So, I've run into this sort of thing a few times in C++ where I'd really like to write something like

case (a,b,c,d) of
     (true, true, _, _ )     => expr
   | (false, true, _, false) => expr
   | ...

But in C++, I invariably end up with something like this:

bool c11 = color1.count(e.first)>0;
bool c21 = color2.count(e.first)>0;
bool c12 = color1.count(e.second)>0;
bool c22 = color2.count(e.second)>0;
// no vertex in this edge is colored
// requeue
if( !(c11||c21||c12||c22) )
{
    edges.push(e);
}
// endpoints already same color
// failure condition
else if( (c11&&c12)||(c21&&c22) )
{
    results.push_back("NOT BICOLORABLE.");
    return true;
}
// nothing to do: nodes are already
// colored and different from one another
else if( (c11&&c22)||(c21&&c12) )
{
}
// first is c1, second is not set
else if( c11 && !(c12||c22) )
{
    color2.insert( e.second );
}
// first is c2, second is not set
else if( c21 && !(c12||c22) )
{
    color1.insert( e.second );
}
// first is not set, second is c1
else if( !(c11||c21) && c12 )
{
    color2.insert( e.first );
}
// first is not set, second is c2
else if( !(c11||c21) && c22 )
{
    color1.insert( e.first );
}
else
{
    std::cout << "Something went wrong.\n";
}

I'm wondering if there's any way to clean all of those if's and else's up, as it seems especially error prone. It would be even better if it were possible to get the compiler complain like SML does when a case expression (or statement in C++) isn't exhaustive. I realize this question is a bit vague. Maybe, in sum, how would one represent an exhaustive truth table with an arbitrary number of variables in C++ succinctly? Thanks in advance.

© Stack Overflow or respective owner

Related posts about c++

Related posts about pattern-matching