confused about pure functions

Adam D. Ruppe destructionator at gmail.com
Sat Mar 17 10:17:33 PDT 2012


In D, pure means it doesn't have any side effects outside
its parameter list.

It can change what you pass in, but nothing else.


Pass it all in, const, or best of all, immutable params
and it can't change anything - that's the pure you're
probably thinking of.



The reason it lets you change the arguments is so you
can use more functions as pure. Consider that you can
have mutable local variables in a pure function - a
local variable doesn't change the outside world, so
it never breaks the contract.

You might want to use a helper function on your local
variables.


Editing a local variable is allowed, so calling a function
that edits a local variable should be allowed too. As far
as the outside world can tell, this is exactly the same thing.

pure void increment(ref int a) { a++; }
int myInt = 0;
increment(myInt); // is logically the same as myInt++;
// we'd allow myInt++;, so we should allow increment(myInt) too.



But, under the strictest definition of pure, that increment
function wouldn't be allowed. Pure functions can only call
other pure functions.


That's why D pure is a little looser: this /should/ be
allowed. Thus, it can be marked as pure.


Does this break the big contract? No, because editing the
params is a purely local modification - the outside world
doesn't need to care how you build your own local variables.


When combined with transitive immutable, you can create
nice pockets of purity while retaining flexibility in
how you implement the function itself. Only what you
pass and get from it is important.


More information about the Digitalmars-d mailing list