Array of structs construction

bearophile bearophileHUGS at lycos.com
Fri Oct 19 18:06:56 PDT 2012


I'd like to write code like this (the constructors of the structs 
must take 1 argument):

// some imports here
void main() {
     BigInt[] data1 = [5, 6, 9];
     Ranged!(int,5,10)[] data2 = [5, 6, 9];
     Nibble[] data3 = [1, 2, 15]; // Nibble.sizeof == 1
     alias Typedef!int Mint;
     Mint[] data4 = [5, 6, 9];
}


Do you like this feature?


Scala accepts a similar syntax:
http://ideone.com/mFuVxP


// Scala code
object Main extends App {
   val data : Array[BigInt] = Array(10, 20, 30)
}


Currently in D you write this, it's not handy if you have many 
items:

// some imports here
void main() {
     auto data1 = [BigInt(5), BigInt(6), BigInt(9)];
     alias Ranged!(int,5,10) R; // a short name
     auto data2 = [R(5), R(6), R(9)];
     auto data3 = [Nibble(1), Nibble(2), Nibble(15)];
     alias Typedef!int Mint;
     Mint[] data4 = [Mint(5), Mint(6), Mint(9)];
}


Or you duplicate the arrays to avoid the bit liberals:

import std.bigint;
void main() {
     auto aux = [5, 6, 9];
     auto data1 = new BigInt[aux.length];
     foreach (i, a; aux)
         data1[i] = BigInt(a);
     // ...
}

Bye,
bearophile


More information about the Digitalmars-d mailing list