A question about purity
Christophe
travert at phare.normalesup.org
Tue Sep 13 05:53:25 PDT 2011
bearophile , dans le message (digitalmars.D.learn:29490), a écrit :
> 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?
No, because you change a variable that is global, even if it is private.
In foo.foo1(), foo is changed, but it can be considered as an argument
and a part of the result of foo1(). You cannot say this for Foo.y.
Here is an example to illustrate what was meant with "encapsulating with
a pure function" :
struct Foo {
int x;
pure int foo1() {
return x++;
}
private static int y;
static pure int foo2() {
return Foo.y++; // not pure: a global variable changes
}
}
pure int test1(Foo foo)
{
auto a = foo.foo1(); // nothing changes outside test1: only the local
// copy of foo changes.
return a;
}
pure int test2()
{
auto b = Foo.foo2(); // error: Foo.y changes
return b;
}
void main()
{
Foo foo;
auto a = test1(foo); // only a copy of foo is changed.
auto b = test1(foo);
assert(a==b); // ok
auto c = test2(); // error: Foo.y changes
auto d = test2();
assert(c==d); // fails if test2 was indeed run twice.
}
More information about the Digitalmars-d-learn
mailing list