www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Array in array

reply "xfiles" <xifles xfire.com> writes:
Hi everybody!
I want create a multi array like python.
For example(in python):
a=[1,2]
a.append([1234],3)
a.append([[4],5],6)

and result is = [1,2,[1234],3,[[4],5],6]

How can I do this in D
Oct 27 2012
next sibling parent reply "BLM768" <blm768 gmail.com> writes:
On Saturday, 27 October 2012 at 21:16:56 UTC, xfiles wrote:
 Hi everybody!
 I want create a multi array like python.
 For example(in python):
 a=[1,2]
 a.append([1234],3)
 a.append([[4],5],6)

 and result is = [1,2,[1234],3,[[4],5],6]

 How can I do this in D
If you want to create it with one line, you can just write something like this: int[] a = [1,2,[1234],3,[[4],5],6]; To build the array by appending to it, the ~= operator appends to an array in place: int[] a = [1,2]; a ~= [[1234],3]; a ~= [[[4],5], 6]; You can also use the ~ operator: a = [1,2,3]; a = a ~ [4, 5]; //a is now [1,2,3,4,5] However, this is less efficient because it makes a copy of the original array. The ~ and ~= operators can also append individual values: a = [1]; a ~= 2; a ~= 3; //a is now [1,2,3]
Oct 27 2012
parent "BLM768" <blm768 gmail.com> writes:
Ack! I just realized that this doesn't work because D isn't 
dynamically typed. I've had way too much Ruby on the brain 
lately...

You could use std.variant to simulate dynamic typing, but can be 
a bit of a mess.
You also could do something like this:

int[][] a = [[1], [2, 3, 4], [5]];

That's also a bit ugly, though.
In the end, you'll probably end up structuring your data in some 
other way.

Next time I answer a question, I'd better make sure I'm thinking 
of the right language.
Oct 27 2012
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
xfiles:

 I want create a multi array like python.
 For example(in python):
 a=[1,2]
 a.append([1234],3)
 a.append([[4],5],6)

 and result is = [1,2,[1234],3,[[4],5],6]

 How can I do this in D
In D there are several different ways to represent that data structure, but being D not dynamically typed (and not having algebraic data types) none of them are as nice as solutions in Python (or ML-derived languages). This shows one way to do it in an efficient way: http://rosettacode.org/wiki/Flatten_a_list#D If efficiency is less important, you can use an heap-allocated multi-way tree. Or even a little hierarchy with two classes. Another solution is to use some kind of variant/any/multi data type. So explain your needs better and maybe someone will suggest what specif solution to use. Bye, bearophile
Oct 27 2012