Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heterogeneous container for D

Tags:

arrays

d

Does D support heterogeneous containers(i.e. an array that holds different types)?

I know about tuples but the limitation of not being "return-able" from functions just kills the purpose I have in mind.

like image 705
Diaa Sami Avatar asked Apr 24 '11 10:04

Diaa Sami


2 Answers

I assume you use D2 because I don't know about D1.

In std.typecons there are tuple and Tuple which allow you to use these "non-returnable" aka compile time tuples you mention to create runtime values.

import std.typecons, std.stdio;

Tuple!(int, string, int[]) f() {
  return tuple(5, "xyz", [3, 4, 5]);
}

void main() {
    auto x = f();
    writefln("%s is %s", x[1], x[0]);
    //indices have to be copile-time constants
}

Use tuple(v1, v2) as the value and Tuple!(T1, T2) as it's type.

If you really want a list of things you don't know the type at compile time import std.variant and then Variant[] as a list of these things.

like image 199
Mafi Avatar answered Oct 19 '22 17:10

Mafi


Variant[] and variantArray() would do the job, here's some examples

module test;

import std.variant, std.stdio;

Variant[] f() {
    return variantArray(5, "xyz", [3, 4, 5]);
}

void main() {
    auto x = f();

    writeln(x); // [5, xyz, [3, 4, 5]]

    writefln("%s is %s", x[1], x[0]); // xyz is 5

    x ~= Variant(890);

    string s = "abc";
    x ~= Variant(s);

    class C {};
    x ~= Variant(new C());

    x ~= Variant(new int[2]);
    x[$-1][0] = 5;

    foreach (e; x) {  
        write(e, " "); // 5 xyz [3, 4, 5] 890 abc test.main.C [5, 0]
    }

    f2(x);

    Variant[] a = variantArray("23", 23);
    Variant[] b = new Variant[3];
    Variant[] c = [Variant(12), Variant("a")];
}

void f2(Variant[] va) {
   writeln(typeid(va)); // std.variant.VariantN!(maxSize).VariantN[]
}
like image 27
fwend Avatar answered Oct 19 '22 17:10

fwend