On Sat, 26 Apr 2014 00:44:13 -0400 Steven Schveighoffer via Digitalmars-d <[email protected]> wrote:
> On Fri, 25 Apr 2014 23:26:29 -0400, Xinok <[email protected]> wrote: > > > On Saturday, 26 April 2014 at 01:57:06 UTC, bearophile wrote: > >> This is one of the largest problems left in the implementation of > >> D purity: > >> > >> https://issues.dlang.org/show_bug.cgi?id=9148 > >> > >> One example of the refused code: > >> > >> > >> void foo(const int[] a) { > >> int bar() pure { > >> return a[0]; > >> } > >> } > >> void main() {} > >> > >> > >> Bye, > >> bearophile > > > > I think this would break the D conventions of purity. 'a' is not > > immutable, only const, meaning one or more elements could change, > > making 'bar' impure. > > It should compile. Purity in D is not the same as the more > traditional definition of purity. > > For example, this compiles: > > int foo(int[] a) pure {return a[0];} > > I see no difference from the above. It's the same, and it isn't. Your example has no access to anything other than a, whereas in bearophile's example, bar has access to its outer scope. So, you can have fun like auto baz = new int[](5); void foo(const int[] a) { int bar() pure { return a[0]; } auto i = bar(); baz[0] = 2; auto j = bar(); } void main() { foo(baz); } Now, if we treat the outer scope like a mutable this pointer (which it probably essentially is underneath the hood), then bar can probably be weakly pure, but we have to be very careful not to consider it strongly pure in spite of the fact that it has no explicit, mutable arguments. Contrast that with int foo(const int[] a) pure { return a[0]; } which is the same as your example save for the const, and that function _can_ be strongly pure if it's passed an immutable array (dmd doesn't currently take strong purity that far - it only treats immutable parameters as strongly pure, not immutable arguments to const parameters -but there's no reason why it couldn't). Your example can't be strongly pure either way though, since its parameter is mutable. In any case, I think that bearophile's example is subtly different from yours, though I think that we can make it weakly pure if we're very careful about how we handle the outer scope. However, I'm not sure that treating it as weakly pure buys us anything except in the case where we're trying to make the outer function pure as well. - Jonathan M Davis
