在D中如何将函数应用于数组中的所有元素?
例如,我想将std.string.leftJustify()函数应用于字符串数组中的所有元素.
我知道我可以使用循环但是有一个很好的地图功能吗?我看到std.algorithm库中有一个,但我还不知道如何在D中使用模板.
任何例子?
eco*_*eco 12
有很多选项可以指定lambda. map返回一个在消耗时懒惰计算的范围.您可以使用函数强制立即评估array从std.array.
import std.algorithm;
import std.stdio;
import std.string;
void main()
{
auto x = ["test", "foo", "bar"];
writeln(x);
auto lj = map!"a.leftJustify(10)"(x); // using string mixins
// alternative syntaxes:
// auto lj = map!q{a.leftJustify(10)}(x);
// auto lj = map!(delegate(a) { return a.leftJustify(10) })(x);
// auto lj = map!(a => a.leftJustify(10))(x); available in dmd 2.058
writeln(lj);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |