Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating ML-style pattern matching in C++

The title says pretty much all, how would I go about simulating ML-style pattern matching in C++, that is for instance;

Statement *stm;
match(typeof(stm))
{
    case IfThen: ...
    case IfThenElse: ...
    case While: ...
    ...
}

Where 'IfThen', 'IfThenElse' and 'While' are classes which inherit from 'Statement'

like image 518
Skeen Avatar asked Aug 12 '13 21:08

Skeen


1 Answers

There was a paper in the C++ committee recently which describe a library that allow to do just that:

Open and Efficient Type Switch for C++ by Stroustup, Dos Reis and Solodkyy
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3449.pdf

A link to a page with source code :
https://parasol.tamu.edu/~yuriys/pm/

Disclaimer : I didn't try to compile or use this library, but it seem to fit your question.

Here is one of the sample provided by the library :

#include <utility>
#include "match.hpp"                // Support for Match statement

//------------------------------------------------------------------------------

typedef std::pair<double,double> loc;

// An Algebraic Data Type implemented through inheritance
struct Shape
{
    virtual ~Shape() {}
};

struct Circle : Shape
{
    Circle(const loc& c, const double& r) : center(c), radius(r) {}
    loc    center;
    double radius;
};

struct Square : Shape
{
    Square(const loc& c, const double& s) : upper_left(c), side(s) {}
    loc    upper_left;
    double side;
};

struct Triangle : Shape
{
    Triangle(const loc& a, const loc& b, const loc& c) : first(a), second(b), third(c) {}
    loc first;
    loc second;
    loc third;
};

//------------------------------------------------------------------------------

loc point_within(const Shape* shape)
{
    Match(shape)
    {
       Case(Circle)   return matched->center;
       Case(Square)   return matched->upper_left;
       Case(Triangle) return matched->first;
       Otherwise()    return loc(0,0);
    }
    EndMatch
}

int main()
{
    point_within(new Triangle(loc(0,0),loc(1,0),loc(0,1)));
    point_within(new Square(loc(1,0),1));
    point_within(new Circle(loc(0,0),1));
}

This is surprisingly clean !

The internals of the library looks a bit more scary though. I did a quick glance and there seems to be quite a lot of advanced macro and meta-programing.

like image 146
Thomas Petit Avatar answered Nov 17 '22 02:11

Thomas Petit