www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 8864] New: Simpler syntax for array literal of structs from one argument

reply d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=8864

           Summary: Simpler syntax for array literal of structs from one
                    argument
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc


--- Comment #0 from bearophile_hugs eml.cc 2012-10-21 14:25:30 PDT ---
I'd like to write code like this (the constructors of the structs must take 1
argument), because it's quite handy in many situations:


// 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];
}


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:

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


A simpler example:

struct Nibble {
    ubyte u;
    this(ubyte ub)
    in {
        assert(ub < 16);
    } body {
        this.u = ub;
    }
}
void main() {
    Nibble[] data = [5, 6];
}


You currently write:

struct Nibble {
    ubyte u;
    this(ubyte ub)
    in {
        assert(ub < 16);
    } body {
        this.u = ub;
    }
}
void main() {
    auto data = [Nibble(5), Nibble(6)];
}


Scala accepts a similar syntax (Scala here probably uses a more general feature
named implicits):


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


See also the discussion thread:
http://forum.dlang.org/thread/tyrleoromnxjhvfodmbe forum.dlang.org

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Oct 21 2012
parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=8864



--- Comment #1 from bearophile_hugs eml.cc 2012-10-21 14:26:37 PDT ---
It's meant to work with 2D arrays too:


struct Nibble {
    ubyte u;
    this(ubyte ub)
    in {
        assert(ub < 16);
    } body {
        this.u = ub;
    }
}
void main() {
    Nibble[][] data = [[1, 2], [3, 4]];
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Oct 21 2012