www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 9909] New: Overloaded foreach can not be used in pure functions

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

           Summary: Overloaded foreach can not be used in pure functions
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: normal
          Priority: P2
         Component: DMD
        AssignedTo: nobody puremagic.com
        ReportedBy: maximzms gmail.com



PDT ---
The following code does not compile if `func` is pure
--------------------
struct Foo
{
    int[3] arr = [1, 2, 3];

    int opApply(int delegate(ref int) loopBody)
    {
        foreach(a; arr)
            loopBody(a);
        return 0;
    }
}

void func() // pure // Error!
{
    Foo foo;
    int sum = 0;
    foreach(f; foo)
    {
        sum += f;
    }
}

void main() {}
--------------------

Pure `func` can not call impure Foo.opApply.
If `Foo.opApply` is pure then it can not call impure `loopBody`.
If `loopBody` is pure then it can not modify "external" variable `sum`.

If `sum` is defined inside loop body there is no error (even with `pure`
keyword everywhere). So I guess DMD examines `foreach` body and finds it pure
in that case.
If that is true then taking into account purity of the function containing the
loop could be a solution.
In that case one would have to define two versions of opApply: for pure and not
pure loop body.

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