T.init for static arrays?
bearophile
bearophileHUGS at lycos.com
Sat Mar 13 13:14:22 PST 2010
Walter Bright:
> What do you think?
Thank you for considering this problem :-) I have posted a request for this few years ago, explaining why it's important for generic code.
In my dlibs1 (for D1) have had to add this Init!() to avoid special-casing many of my functions:
ReturnType!({T result; return _recordinit(result);}) Init(T)() {
T result;
return _recordinit(result);
}
struct _Recordinit(T) { T init; }
_Recordinit!(T) _recordinit(T)(T args) {
return _Recordinit!(T)(args);
}
And recently I have added this bug report:
http://d.puremagic.com/issues/show_bug.cgi?id=3826
So I think it's useful to fix this.
> It is done this way for memory efficiency, as:
> a = A.init;
> doesn't need to create an array for the rvalue.
It's the first I see an explanation of why it's done this way.
The following examples are written in the page about arrays:
http://www.digitalmars.com/d/2.0/arrays.html
s[] = t; // the 3 elements of t[3] are copied into s[3]
s[] = t[]; // the 3 elements of t[3] are copied into s[3]
s[] = 3; // same as s[0] = 3, s[1] = 3, s[2] = 3
p[0..2] = 3; // same as p[0] = 3, p[1] = 3
Following Python Zen, I don't like to have two different syntaxes to do the same thing, so this can become a syntax error:
int[3] a, b;
a[] = a;
So you must write:
int[3] a, b;
a[] = a[];
This is also allowed:
int[3] a;
int i;
a[] = i;
This has to be a syntax error:
int[3] a;
int i;
a[] = i[];
So once array.init is [init, init, ...] this will be allowed (but can't the compiler recognize and optimize this situation in many cases?):
int[3] a;
a[] = a.init[];
To save memory the programmer can use:
int[3] a;
a[] = a[0].init;
------------------------
Regarding the assert(float.init is NaN) and the "is" meant as binary compare I don't mind it. Making the language more orthogonal and removing special cases reduces language complexity in programmes heads, books, and makes generic code simpler.
Bye and thank you,
bearophile
More information about the Digitalmars-d
mailing list