D中的模式匹配

KIM*_*IMA 21 functional-programming d pattern-matching

我最近偶然发现了D编程语言,我非常喜欢它.你可以编程真正的高级别,同时拥有完整的硬件访问,如在C.

来自一个相当功能性的背景(Haskell,scala)我正在寻找D模式匹配的方法,但我在http://www.digitalmars.com/d/上找不到任何东西.在Haskell中,语言本身支持模式匹配.在Scala中,它通过case类或提取器(具有unapply方法的普通对象)实现.

可以在D中执行此操作吗?

std.concurrency中的receive方法用于在actor类式中进行并发,就像在erlang和scala中一样,在这些方法上采用了大量的函数和模式数学.但我认为它不像其他语言那样灵活.你能用卫兵吗?你能在scala中提取Object的内容吗?

Mic*_*ich 10

Haskell中已知的模式匹配没有内置到语言中,但是D具有非常通用的编译时间和反射功能,允许您在库中匹配类型及其结构.对于匹配的运行时值,您只能使用普通的if/ switch...构造; 对函数参数的惰性求值也可能有助于实现一些运行时匹配技术.

模板约束将允许您基于在编译时评估的任何表达式创建函数(模板)重载(D允许您在编译期间执行几乎所有正常代码).您也可以使用static if类似的效果.这实际上允许您匹配类型结构.这也是D中常用的技术.

您可能会发现std.algorithm的代码有趣,查找isInputRange和类似函数 - 它们在类型结构上执行匹配 - 它们将参数类型限制为某些类型类

编译时反思的一些方向:


小智 8

没有像Haskell或Scala那样强大的专用模式匹配功能.

正如您已经想到的那样,重载和调用(模板化)函数或委托是一种受限制的模式匹配形式.您只能匹配参数类型.

您可以在编译时模板参数上进行模式匹配.也无法在那里提取对象的内容.但是你可以提取类型的内容.

例如:

import std.stdio, std.conv;
template match(T...){
    enum match = "default case";
}
template match(string a : "x", int b : 1, int  c){
    enum match = "matched 1, b="~to!string(b);
}
template match(int a, string b, int c : 100){
    enum match = "matched 2, b="~b;
}
template match(T : T[]*[]){
    enum match = "matched 3, an array of pointers to an array of "~T.stringof;
}


void main(){
    int a=100;
    writeln(match!("x",1,5));        // "matched 1, b=1"                                                                                                     
    writeln(match!(12,"str"));       // "default case"                                                                                                       
    writeln(match!(12,"str",100));   // "matched 2, b=str"                                                                                                   
    writeln(match!(int*[]*[]));      // "matched 3, an array of pointers to an array of int*"                                                                
    //writeln(match!(12,"str",a));   // would be error, because 'a'                                                                                            
                                     // is not evaluable during compile time                                                                                 
}
Run Code Online (Sandbox Code Playgroud)

如果您有兴趣,可以查看http://d-programming-language.org/template.html.

'is' - 表达式是模式匹配类型的另一种方式,请参阅

http://d-programming-language.org/expression.html(搜索"IsExpression").