用C ++模拟ML样式模式匹配

时间:2013-08-12 21:48:02

标签: c++ pattern-matching

标题几乎全部说明,我将如何在C ++中模拟ML样式模式匹配,例如;

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

'IfThen','IfThenElse'和'While'是继承自'Statement'的类

1 个答案:

答案 0 :(得分:19)

最近在C ++委员会中有一篇论文描述了一个允许这样做的库:

Stroustup,Dos Reis和Solodkyy开放且高效的C ++类型切换 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3449.pdf

指向包含源代码的页面的链接:
https://parasol.tamu.edu/~yuriys/pm/

免责声明:我没有尝试编译或使用此库,但它似乎适合您的问题。

以下是图书馆提供的样本之一:

#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));
}

这非常干净!

图书馆的内部看起来有些可怕。我快速浏览了一下,似乎有很多高级宏和元编程。