自动柯里化
f(a,b,c)
按
f(a)(b)(c)
调用.
template autocurry(alias what) {
import std.traits;
static if(Parameters!what.length)
auto autocurry(Parameters!what[0] arg) {
alias Remainder = Parameters!what[1 .. $];
auto dg = delegate(Remainder args) {
return what(arg, args);
};
static if(Remainder.length > 1)
return &autocurry!dg;
else
return dg;
}
else
alias autocurry = what;
}
int foo(int a, string b, float c) {
import std.stdio; writeln(a, " ", b, " ", c);
return 42;
}
string test() {
import std.stdio; writeln("调用测试");
return "无参";
}
void main() {
import std.stdio;
alias lol = autocurry!foo;
writeln(lol(30)("lol")(5.3));
auto partial = lol(20);
partial("wtf")(10.5);
alias t = autocurry!test;
writeln(t());
}
想法
很简单:如果有,根据
剩余
参数生成
辅助
函数,按
闭包
返回
辅助
函数
地址
,否则,只返回调用
收集
参数的
闭包
.递归处理
多参
,而外部
静如
仅返回
原始
函数来处理
无参
.
alias lol = autocurry!foo;
//lol为占位符,
int foo(int a, string b, float c) {
import std.stdio;
writeln(a, " ", b, " ", c);
return 42;
}
alias foo = autocurry!foo;
//用原foo重载自动柯里foo
//使用
void main() {
foo(30)("lol")(5.3); // 柯里版
foo(40, "cool", 103.4); // 原版
}