Array Operations question
bearophile via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 25 08:43:57 PDT 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
More information about the Digitalmars-d-learn
mailing list