d的自动柯里化
自动柯里化
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());
}
想法
很简单:如果有,根据剩余
参数生成辅助
函数,按闭包
返回辅助
函数地址
,否则,只返回调用收集
参数的闭包
.递归处理多参
,而外部静如
仅返回原始
函数来处理无参
.
需要注意的语言特征
:
1,同名模板
.模板
具有与模板
同名的成员
时(在本例中为autocurry
),使用
时会自动引用
它.
2,扩展
元组.调用(arg,args)
时,内置
元组的args
会自动扩展
来创建完整参数列表
.
3,各种自动返回(不指定返回类型
的显式auto autocurry
和隐式delegate
关键字),只是转发返回
的其他随机类型.
4,main
函数中,
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); // 原版
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现