Will compiler-enforced pure be too strict?
Craig Black
craigblack2 at cox.net
Thu Apr 3 11:50:20 PDT 2008
Don Clugston wrote:
>A function which accesses a global is inherently impure. But,
>a function which takes a non-invariant argument, can in theory safely be
>called
>from inside a pure function, provided any non-invariant arguments are local
>variables, or invariant.
>
>eg.
>
>class C
>{
> int numcalls;
> this() { numcalls=0; }
> void foo() { ++numcalls; } // Not pure - but no global side effects.
>}
>
>pure int bar(int x)
>{
> C c = new C;
> for (int i=0; i<x; ++i) c.foo();
> return c.numcalls;
>}
>
>Is bar() pure or not?
>
>Incidentally this type of code currently works in CTFE.
The answer is yes bar is pure even though foo is not, because c is a local
variable, so it's non-static fields won't be accessed by other threads.
Unless I misunderstand, the rule is that a non-static class/struct variable
that is local to a pure function can call a member function if that member
function does not access global state.
My question is, will the compiler be smart enough to know that bar is pure,
even though foo is not? Maybe we need some other keyword to denote that a
function does not access any global/static variables. Something like this:
localstate void foo() { ++numcalls; }
Or perhaps the compiler would be smart enough to know this without the
keyword?
-Craig
More information about the Digitalmars-d
mailing list