【问题标题】:Simulating ML-style pattern matching in C++在 C++ 中模拟 ML 样式的模式匹配
【发布时间】:2013-08-14 16:32:35
【问题描述】:

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

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

其中 'IfThen'、'IfThenElse' 和 'While' 是继承自 'Statement' 的类

【问题讨论】:

  • 您可能正在寻找Visitor pattern
  • 我考虑过访问者模式,希望有更优雅的东西!
  • 明智地使用 Boost.Variant 和元组可以模仿代数数据类型的使用。 (变体和元组通常都提供解构其值的方法。)

标签: c++ pattern-matching


【解决方案1】:

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

这出奇的干净!

不过,图书馆的内部结构看起来有点吓人。我快速浏览了一下,似乎有很多高级宏和元编程。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-04-06
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多