array concatenation issue? or me being stupid

Tobias Kieslich tobias at justdreams.de
Tue Mar 18 00:02:22 PDT 2008


Hi,

dmd version was 2.012 for this.

	I'm sorry if that should have gone to learn-d but it also might be a
bug. Anyway, I'm here to to get some insight.
Coming from scripting languages (Python, JavaScript as fnctional
language, etc) I try to come to terms with the rules of a language like
D.
I tried some array concatenation the other day to figure out about when
I can use a~=1 vs a~=[1]. Where the first strongly resambles constructs
like a.append(1) and the latter a += [1] in python. Anyway, approaching
multidimensional arrays I ran into an obvious issue, that I have to
write:

	int [][] a =[[0,1],[2,3]];
	a ~= [4,5];    //fail
	a ~= [[4,5]];  //success

because D inspects the first element of an array to determine it's type.
Now, here it is where it gets weird. Dynamic arrays of static arrays:

	int [2][] b =[[0,1],[2,3]];
	b ~= [[4,5]];  // fail, because concatenate [2u][] with [][1u]
	b ~= [4,5];    // success but wrong result as b holds now:
	// [[0 1] [2 3] [4 5] [0 0]]

How do I concatenate that properly?

Thanks,
	Tobias

some readyly compilable sample code:

import std.stdio;

int main() {
	writefln("multi dim arrays -- dynamic");
	/// multi dimensional arrays
	int [][] a = [[1,2],[3,4]];
	writefln("%s --- length: %d", a, a.length);
	//a = a ~ [9,10];
	a = a ~ [[9,10]]; // success, can concatenate 2 arrays of same type and structure
	writefln("%s --- length: %d", a, a.length );
	// success, D knows only that it's an array of arrays, not about the length of the arrays
	// because we initialized as dynamic arrays
	a = a ~ [[11,12,13]];
	writefln("%s --- length: %d", a, a.length );


	writefln("\nmulti dim arrays -- dynamic of static");
	int [2][] y = [[1,2],[3,4]];
	writefln("%s --- length: %d", y, y.length );
	//y = y ~ [[9,10]]; // fail because concatenate [2u][] with [][1u]
	y = y ~ [9,10]; // success, but wrong result
	writefln("%s --- length: %d", y, y.length );
	// fail, because we initialized as arrays of static length of 2
	//y = y ~ [11,12,13];

	return 1;
}



More information about the Digitalmars-d mailing list