Bug 9909 – Overloaded foreach can not be used in pure functions
Status
RESOLVED
Resolution
WORKSFORME
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-04-09T02:57:40Z
Last change time
2021-10-26T13:08:32Z
Assigned to
No Owner
Creator
Maksim Zholudev
Comments
Comment #0 by maximzms — 2013-04-09T02:57:40Z
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.
Comment #1 by moonlightsentinel — 2021-10-26T13:08:32Z
Works since 2.067.1 if `opApply` and `loopBody` are marked as pure