在C ++中模拟ML风格模式匹配 [英] Simulating ML-style pattern matching in C++

查看:151
本文介绍了在C ++中模拟ML风格模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎全部,我将如何去模拟在C ++中的ML风格模式匹配,例如;

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: ...
    ...
}



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

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

推荐答案

C ++委员会最近有一篇论文描述了一个库, :

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

Stroustup,Dos Reis和Solodkyy为C ++打开和有效的类型切换

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3449.pdf

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

指向包含源代码的页面的链接:

https://parasol.tamu.edu/~yuriys/pm/

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.

这篇关于在C ++中模拟ML风格模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆