A question about purity

Jonathan M Davis jmdavisProg at gmx.com
Mon Sep 12 15:58:25 PDT 2011


On Monday, September 12, 2011 15:24 bearophile wrote:
> A D2 program:
> 
> 
> struct Foo {
> int x;
> static int y;
> pure void foo1() {
> this.x++;
> }
> static pure void foo2() {
> Foo.y++; // line 8, error
> }
> }
> void main() {}
> 
> 
> With DMD 2.055 it gives at compile-time:
> test.d(8): Error: pure function 'foo2' cannot access mutable static data
> 'y'
> 
> If a (weakly?) pure method foo1 is allowed to change instance attributes,
> do you know why a static (weakly?) pure method can't change static
> attributes? What's the purity difference between foo1 and foo2? I cant'
> see a lot of difference.

In foo1, this is one of its arguments - albeit an invisible one. In foo2, y is 
not one of its arguments. If a strongly pure function allocates a Foo, it can 
know that when it calls foo1 that nothing outside of that Foo is altered by 
the call. All of the arguments to foo1 are encapsulated in the strongly pure 
function and affect nothing outside of it. However, Foo.y is not encapsulated 
by a strongly pure function at all. Other functions can alter alter it. So, it 
breaks purity.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list