One case of array assignments
Timon Gehr
timon.gehr at gmx.ch
Wed Mar 13 14:49:25 PDT 2013
On 03/13/2013 10:19 PM, John Colvin wrote:
> On Wednesday, 13 March 2013 at 21:08:30 UTC, Timon Gehr wrote:
>> ...
>>
>> That's clearly a valid way of reasoning, however, it is not the only one.
>>
>> int[3] a = 1;
>> int[3] b = 2;
>> int[3] c = 3;
>>
>> int[3][3] x = [a,b,c];
>
> this would also be valid, as you have fully specified the elements of
> the array. I don't see the conflict?
This was supposed to be a justification for int[3][3] x = [1,2,3];
denoting int[3][3] x = [[1,1,1],[2,2,2],[3,3,3]];
I think any one way to define the initialization semantics is arbitrary.
It is not necessary anyway, the language is versatile enough:
import std.stdio : writeln;
import std.algorithm, std.range;
auto array(R)(R r){ // phobos' version still not ctfe-able...
typeof({foreach(x;r)return x;assert(0);}())[] a;
foreach(x;r) a~=x;
return a;
}
auto erep(R)(R r, size_t n){ return r.repeat(n).array; }
auto emap(alias a, R)(R r){ return r.map!a.array; }
auto rows(T)(T[] x,size_t n){ return x.erep(3); }
auto cols(T)(T[] x,size_t n){ return x.emap!(a=>a.erep(3)); }
int[3][3] x = [1,2,3].rows(3);
int[3][3] y = [1,2,3].cols(3);
void main(){
assert(x[]==[[1, 2, 3], [1, 2, 3], [1, 2, 3]]);
assert(y[]==[[1, 1, 1], [2, 2, 2], [3, 3, 3]]);
}
(using one of bearophiles turned-down enhancement requests:
int[$][$] x = [1,2,3].rows(3);
int[$][$] y = [1,2,3].cols(3);
)
More information about the Digitalmars-d
mailing list