Global const variables

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 21 10:09:57 PDT 2014


On Tuesday, 21 October 2014 at 15:51:27 UTC, MachineCode wrote:
> pure functions are also supposed to don't use global variables 
> at all, according to functional programming paradigm

The functional programming paradigm is kind of irrelevant to D's 
pure, which should really be something more like @global. D's 
pure makes it so that a function cannot directly access global, 
mutable state - i.e. no mutable global or static variables which 
can ever be mutated by anything in the program. So, pure 
functions can access immutable global and static variables, 
because their state can never change, and in principle, they 
could access const variables that were directly initialized, e.g.

const int i = 7;

However, apparently, the compiler won't do that with arrays right 
now, as Bearophile has found. Accessing global or static 
variables that can never change once they're initialized does not 
violate the guarantees that D's pure makes, because the value is 
fixed and as such is essentially the same as hard-coding the 
value in the function directly. It's just those that can change 
which are a problem (which does potentially include global, const 
arrays if they were initialized via a static constructor).

Now, while D's pure really doesn't directly have anything to do 
with functional purity (_all_ it does is restrict access to 
global or static variables which can be mutated - either directly 
or indirectly), it _is_ a vital building block for functional 
purity, because if the function parameters are immutable or 
implicitly convertible to immutable, then the compiler knows that 
multiple calls to the function with the same arguments will 
always return the same result, because the function can't access 
any mutable globals to get at anything different to produce a 
different result. And even if the parameters aren't immutable or 
implicitly convertible to immutable, if the parameter types and 
return type are unrelated, the compiler can also know that the 
return value was not passed into the function (since it had 
nowhere else to get it from), so it knows that it's unique and 
can do stuff like implicitly convert that value to immutable 
safely.

So, with pure, the compiler can recognize actual, functional 
purity and other useful attributes and take advantage of them, 
but you're probably better off if you don't think of D's pure as 
being functionally pure, because there are quite a few things 
that D's pure functions can do which functionally pure functions 
can't do (like mutate their arguments if they're mutable).

A good article on D's pure: 
http://klickverbot.at/blog/2012/05/purity-in-d/


More information about the Digitalmars-d-learn mailing list