Search code examples
d

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


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?


Solution

  • 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);
    }