www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 5489] New: std.typecons tuples dynamically iterable

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

           Summary: std.typecons tuples dynamically iterable
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc



std.typecons tuples are not arrays, and their items don't need to be all of the
same type. But in Python programming with tuples I have seen that once in a
while it's useful to iterate on their items.

Currently in D2 (DMD 2.051) you are allowed to iterate on tuple items, but this
is a "static foreach":

import std.stdio, std.typecons;
void main() {
    auto t = tuple(1, 2, 3, 4);
    /*static*/ foreach (x; t.tupleof)
        writeln(x);
}


This is dynamic:

import std.typecons, std.algorithm;
void main() {
    auto t = tuple(1, 2, 3, 4);
    auto total = reduce!q{a + b}([t.tupleof]);
    assert(total == 10);
}


But in some situations with usage of zip and other things it's not handy to
convert tuples in arrays in that way. So I'd like tuples made of the same type
of items (castable) to be iterable (a "static if" disables the range protocol
methods if std.traits.CommonType applied on the tuple items is void):

import std.typecons, std.algorithm;
void main() {
    auto t = tuple(1, 2, 3, 4);
    auto total = reduce!q{a + b}(t);
    assert(total == 10);
}


With sum() from bug 4725 it becomes:

import std.typecons, std.algorithm;
void main() {
    auto t = tuple(1, 2, 3, 4);
    auto total = reduce!sum(t);
    assert(total == 10);
}


Another hypotetical example usage:

import std.typecons, std.algorithm, std.range;
void main() {
    auto t1 = tuple(1, 2, 3, 4);
    auto t2 = tuple(10, 20, 30, 40);
    auto r = map!sum(zip(t1, t2));
    assert(r == [11, 22, 33, 44]);
}


Equivalent Python2 working code:

 t1 = (1, 2, 3, 4)
 t2 = (10, 20, 30, 40)
 map(sum, zip(t1, t2))
[11, 22, 33, 44] -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------
Jan 26 2011