How to initialize an immutable array
bearophile
bearophileHUGS at lycos.com
Fri Mar 1 12:31:02 PST 2013
Sparsh Mittal:
> So, is there a way, an array can be made immutable and still
> initialized? Thanks a lot for your time.
There are various ways to do it. One of the safest way to do it
is to create a mutable array inside a strongly pure function, and
then when you return it assign it to immutable:
import std.stdio, std.datetime, std.range;
double myAbs(in double n) pure nothrow {
return n > 0 ? n : -n;
}
enum long DIM = 1024L * 1024L * 128L;
double[] genSignal() pure nothrow {
auto signal = new double[DIM + 1];
foreach (immutable i; 0 .. DIM + 1) {
signal[i] = (i + DIM) % 7 + (i + DIM + 1) % 5;
}
return signal;
}
void main() {
immutable signal = genSignal();
double sample[2] = [4.1, 7.2];
StopWatch sw;
sw.start;
foreach (immutable i; 0 .. DIM) {
double temp = myAbs(sample[0] - signal[i]) +
myAbs(sample[1] - signal[i + 1]);
}
sw.stop;
writeln(" Total time: ", sw.peek.msecs / 1000, "[sec]");
}
A less safe way to do it is to use assumeUnique from Phobos.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list