[Issue 7666] A function to reverse the items of a tuple

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Oct 27 15:07:18 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=7666


Andrej Mitrovic <andrej.mitrovich at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |andrej.mitrovich at gmail.com


--- Comment #1 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2012-10-27 15:07:05 PDT ---
First thing I could come up with, but it requires editing the Tuple!() struct.
A public alias is added in Tuple struct:

alias Reverse!fieldSpecs revFieldSpecs; 

And the internal FieldSpec struct is moved outside and made public. Then the
following is possible:


auto reversed(T)(T tup)
    if (isTuple!T)
{
    static string getMixin(T)()
    {
        string[] result;
        foreach (i; 0 .. T.Types.length)
        {
            result ~= xformat("tup.field[%d]", i);
        }

        return result.retro.join(", ");
    }

    static string getSpecs(T)()
    {
        string[] result;
        foreach (spec; T.revFieldSpecs)
        {
            result ~= spec.Type.stringof;
            result ~= xformat(`"%s"`, spec.name);
        }

        return result.join(", ");
    }

    enum str = xformat("return Tuple!(%s)(%s);", getSpecs!(T)(),
getMixin!(T)());
    mixin(str);
}

void main()
{
    alias Tuple!(int, "index", string, "value") Entry;
    Entry e;
    e.index = 4;
    e.value = "Hello";

    auto rev = reversed(e);
    assert(e.index == 4);
    assert(e.value == "Hello");
    writeln(e);
    writeln(rev);
}

Prints:
Tuple!(int,"index",string,"value")(4, "Hello")
Tuple!(string,"value",int,"index")("Hello", 4)

If there is a non-invasive way of doing this it would be welcome.

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


More information about the Digitalmars-d-bugs mailing list