On Monday, 23 June 2014 at 22:11:57 UTC, John Carter wrote:
On Monday, 23 June 2014 at 21:49:29 UTC, Ary Borenszweig wrote:

Union types are very common (I use them every day), and IMHO it's very nice to have them included in the language (either built-in or as a library solution). As a library solution I would do something like this:

Union!(int, string)[] elements;

Hmm. egrepping through /usr/include/dmd fails to find '\bUnion\b', are you sure you don't mean Algebraic?

You're looking for std.variant.Algebraic and std.typecons.Tuple. Tuple is actually a library-defined struct, with no compiler magic. The tuple situation in D is a bit weird; there are compiler tuples (which you don't need to worry about in this case), and library tuples, i.e., std.typecons.Tuple. There's also at least 1 other kind of special tuple, but you should hardly ever need to deal with that. For most cases, just use std.typecons.Tuple. Here's a few simple examples:

import std.typecons: Tuple;

Tuple!(string, File[]) getDirListing(string dir)
{
    //...
}

//Even better
alias DirListing = Tuple!(string, File[]);

DirListing getDirListing(string dir)
{
    //...
}

//Adding a string after a tuple member names that field
alias DirListing = Tuple!(string, "dir", File[], "files");

void main()
{
    //These functions for operating on files are just made up
    enum directory = "C:\SomeDir";
    auto dirListing = getDirListing(directory);
    foreach (i, file; dirListing.files)
    {
        file.setName("%s-%s".format(dirListing.name, i);
    }
}

Reply via email to