Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiomatic D way to produce an array containing the integers from 1 to n?

Tags:

d

Often in D I want to do something like:

uint n;
foreach(uint i; parallel(1..n)){
    somefunc(i);
}

That is, I want to make n calls to a function (somefunc) in parallel, using the integers 1 to n as arguments.

However, dmd doesn't seem to like 1..n here, so I end up doing goofy things like:

uint n;
int[] nums = new int[n];
foreach(ulong index, int value; parallel(nums)){
    sumfunc(index);
}

Is there an idiomatic way to write this in D? Something that doesn't involve the creation of needless extra variables?

like image 460
John Doucette Avatar asked Aug 08 '14 20:08

John Doucette


1 Answers

Take a look at std.range.iota. It's better than an array because it makes no allocations.

void main()
{
    import std.parallelism, std.range;
    foreach(i; parallel(iota(1, 100))){
        somefunc(i);
    }
}

void somefunc(uint i)
{
    import std.stdio;
    writeln(i);
}
like image 163
eco Avatar answered Jan 01 '23 19:01

eco