Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate an array in D?

Tags:

arrays

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.

like image 670
Arlen Avatar asked Oct 11 '22 00:10

Arlen


1 Answers

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.

like image 88
FeepingCreature Avatar answered Oct 18 '22 08:10

FeepingCreature