How do I generate an array in D?
I have this c++11 code:
auto gen = []() -> double { /* do stuff */ };
std::generate(myArray.begin(), myArray.end(), gen);
How would I do the same with D's array? std.algorithm.fill
doesn't take a function object, and I don't know how to pass a function to 开发者_高级运维recurrence
.
Here's a version that seems to work:
import std.algorithm, std.array, std.range, std.stdio;
void main() {
writefln("%s", __VERSION__);
int i;
auto dg = delegate float(int) { return i++; };
float[] res = array(map!dg(iota(0, 10)));
float[] res2 = new float[10];
fill(res2, map!dg(iota(0, res2.length)));
writefln("meep");
writefln("%s", res);
writefln("%s", res2);
}
[edit] Added fill-based version (res2).
I tested it in Ideone (http://www.ideone.com/DFK5A) but it crashes .. a friend with a current version of DMD says it works though, so I assume Ideone's DMD is just outdated by about ten to twenty versions.
You could do something like
auto arr = {/* generate an array and return that array */}();
If it's assigned to a global it should be evaluated at compile-time.
You can also use string mixins to generate code for an array literal.
精彩评论