Simulating ML-style pattern matching in C++ -


the title says pretty all, how go simulating ml-style pattern matching in c++, instance;

statement *stm; match(typeof(stm)) {     case ifthen: ...     case ifthenelse: ...     case while: ...     ... } 

where 'ifthen', 'ifthenelse' , 'while' classes inherit 'statement'

there paper in c++ committee describe library allow that:

open , efficient type switch c++ stroustup, dos reis , solodkyy
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3449.pdf

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

disclaimer : didn't try compile or use library, seem fit question.

here 1 of sample provided library :

#include <utility> #include "match.hpp"                // support match statement  //------------------------------------------------------------------------------  typedef std::pair<double,double> loc;  // 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 surprisingly clean !

the internals of library looks bit more scary though. did quick glance , there seems quite lot of advanced macro , meta-programing.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -