templates - D中的柯里化函数模板?
问题描述
是否可以编写可用于在 D 中自动柯里化函数的模板或类似内容?手动写出所有嵌套的代表正在杀死我。
基本上,对于f
具有例如 3 个参数的函数,通常可以调用为f(a,b,c)
,我希望它可以调用为f(a)(b)(c)
。
我知道std.functional.partial,但这不是我想要的。我想翻译函数定义端,而不是调用端。
我也知道这远非最佳实践,但我正在生成代码,所以请耐心等待。
解决方案
好吧,这些方面的东西应该可以完成这项工作:
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("called test");
return "no args";
}
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());
}
想法很简单:根据剩余的参数生成辅助函数 - 如果有,则返回辅助函数的地址作为委托,否则,只返回调用收集的参数的委托。一点点递归处理 1+ arg 情况,而外部的静态 if 通过仅返回原始函数来处理 0 arg 情况。
需要注意的语言特征:
同名模板。当模板具有与模板同名的成员时(在本例中为 autocurry),使用时会自动引用它。
元组扩展。当我调用
what(arg, args)
时args
,作为内置元组的那个会自动扩展以创建完整的参数列表。这里的各种自动返回(没有指定返回类型的显式
auto autocurry
和隐式delegate
关键字)只是转发正文碰巧返回的任何其他随机类型。在 main 函数中,我做了
alias lol = autocurry!foo;
(我经常使用 lol 作为占位符名称,lol)。您也可以在顶层重载它:
int foo(int a, string b, float c) {
import std.stdio; writeln(a, " ", b, " ", c);
return 42;
}
alias foo = autocurry!foo; // overloads the auto-curried foo with the original foo
现在您可以直接使用它,与原始版本一起使用:
void main() {
foo(30)("lol")(5.3); // overload resolves to curried version
foo(40, "cool", 103.4); // overload resolves to original automatically
}
如果您更喜欢新名称或重载由您决定,则任何一个都可以。
请注意,每个参数都可能分配一些内存来为下一个委托存储它。GC 将负责清理它。
推荐阅读
- c# - 有没有办法使用字符串在循环中声明新变量?
- struct - Option 类型是否小于包装类型加上布尔值?
- r - 删除具有负值的行时出现奇怪的结果
- puppeteer - 如何创建与 puppeteer 页面完全一样的 PDF?
- solr - Solr 中的 Edismax 查询对不同的字段使用不同的字符串
- typescript - 摆脱Vscode的cmd点击内联窗口,直接导航到代码
- flutter - PopMenu dropDown onChanged 不改变视图上的当前值
- android - Oncomplete 任务在 getResult() 之后无法访问方法 getDownloadUrl()
- multiprocessing - astropy 多处理访问 IERS 数据
- javascript - 符号作为 Firefox 中 Javascript 对象的关键标识符