没有像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
}
如果你有兴趣,你可能想看看http://d-programming-language.org/template.html。
'是' - 表达的是另一种类型上的模式匹配,见
http://d-programming-language.org/expression.html(搜索 “Is表达式”)。
嗯......你说的模式匹配究竟是什么意思?你在谈论逻辑编程吗? – Mehrdad 2011-06-11 17:06:12
@Mehrdad我认为Haskell中的模式匹配有点像C++中的模板特化。 – Arlen 2011-06-11 20:59:09
@红:呃......我不确定我明白为什么它叫做模式匹配。说它像Scheme一样是否正确(因为lambdas和宏几乎都是模式匹配器)?如果是这样,那么我想我会看到我们要去的地方。 – Mehrdad 2011-06-11 21:04:42