July 25, 2014
Hello!

I started exploring D today and one of the things that caught my attention was the "array operations" feature.

While playing around and writing some code with it, I came across a problem I wasn't able to find a solution for. The following is a simple example of the assignment array operator to initialize an array.

float[10] a;
a[] = uniform(0.0f, 1.0f);

This is going to set all values to the result of a single call to uniform();

Is there a way to express my intent that I want one result per array element?
July 25, 2014
Márcio Martins:

> float[10] a;
> a[] = uniform(0.0f, 1.0f);
>
> This is going to set all values to the result of a single call to uniform();
>
> Is there a way to express my intent that I want one result per array element?

Currently D array operations can't be used for that kind of usage. So you have to use a normal foreach loop:

void main() {
    import std.stdio, std.random;

    float[10] a;

    foreach (ref x; a)
        x = uniform01;

    a.writeln;
}


Or you can also use ranges, in a functional style:


void main() {
    import std.stdio, std.range, std.random, std.algorithm;

    float[10] a;

    a
    .length
    .iota
    .map!(_ => uniform01)
    .copy(a[]);

    a.writeln;
}

Bye,
bearophile