Enhancing foreach
bearophile
bearophileHUGS at lycos.com
Wed Jan 9 19:43:48 PST 2013
Jonathan M Davis:
> I use it when I need it,
I think there many usages of iota that you are missing. To spot
those cases you probably need to train yourself a bit. A Python
programmer doesn't need that training.
> I can't remember the last
> time that I needed to generate a range of numbers for anything.
There are hundreds of use cases. Some examples:
To create a row of an identity matrix (j is the row number):
iota(n).map!(i => cast(T)(i == j))()
A short matrix transpose:
auto transpose(T)(in T[][] m) {
return iota(m[0].length).map!(i => transversal(m, i))();
}
To write progressive numbers in a textual table:
string result = format("N. flags: %d\n %(%d%)",
n_flags, iota(1, n_columns + 1));
Or to generate the ticks on the table rows:
auto line = iota(m).map!(_ => std.array.replicate(["+--"], n))()
To generate a table of random numbers:
auto randoms = iota(n).map!(_ => uniform(0.0, 1.0))().array();
More usages with random numbers:
bool isIn(int) {
return hypot(uniform(0.0, 1.0), uniform(0.0, 1.0)) <= 1;
}
double pi(in int n) {
return 4.0 * count!isIn(iota(n)) / n;
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list