A question about purity
Jonathan M Davis
jmdavisProg at gmx.com
Tue Sep 13 08:21:49 PDT 2011
On Tuesday, September 13, 2011 07:43:55 bearophile wrote:
> Jonathan M Davis:
> > However, Foo.y is not encapsulated
> > by a strongly pure function at all. Other functions can alter alter it.
> > So, it breaks purity.
>
> Thank you for your explanation :-)
>
> So, let's change the situation a bit. If the struct Foo is the only thing
> present in a module (to avoid someone to touch its private members), and
> the y field is "private static" only foo2 is able to touch it. In this case
> isn't foo2 weakly pure?
>
>
> struct Foo {
> private static int y;
> static pure void foo2() {
> Foo.y++;
> }
> }
> void main() {}
Pure functions cannot access mutable static variables. End of story. _That_ is
the definition of pure in D. The terms strong and weakly pure relate only to
whether a particular call to a pure function can be optimized out, and Don
(who created the terms) would like to see the terms die out.
Yes, in this particular situation, if you treat everything in the program as
an argument to the function (which is completely impractical), then you know
that calling foo2 won't break purity. But that's just way too complicated. The
compiler doesn't work that way and never will. And there would be no point in
making it work that way even if it were feasible, because this example is
completely contrived. It's just not going to happen in real life.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list