[Issue 3444] New: foreach(i, elem; range) should work

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Oct 26 18:39:00 PDT 2009


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

           Summary: foreach(i, elem; range) should work
           Product: D
           Version: 2.035
          Platform: Other
        OS/Version: Windows
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: dsimcha at yahoo.com


--- Comment #0 from David Simcha <dsimcha at yahoo.com> 2009-10-26 18:38:59 PDT ---
Currently, one cannot do a foreach statement over a range that also gives the
index.  This is inconsistent with arrays.  I'm not sure if it's the best fix,
but at least a temporary fix is to mix this thing into all ranges:

template CountForeach(I) {
    int opApply(int delegate(ref I, ref typeof(this.front())) dg) {
        I index = 0;
        int result;
        foreach(elem; this) {
            result = dg(index, elem);
            if(result) {
                break;
            }
            ++index;
        }

        return result;
    }
}

Usage:

struct SomeRange {

    SomeType front() { return something; }

    void popFront() {  
        doStuff();
    }

    bool empty() {
        return amIEmpty();
    }

    mixin CountForeach!size_t;
}

void main() {
    SomeRange someRange;

    foreach(elem; someRange) {}  // Uses range interface directly.

    foreach(i, elem; someRange) {}  // Uses the mixin;
}

-- 
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