pure functions

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 13 13:33:08 PDT 2016


On 9/13/16 4:08 PM, Patrick Schluter wrote:
> On Tuesday, 13 September 2016 at 06:59:10 UTC, Jonathan M Davis wrote:
>> On Tuesday, September 13, 2016 03:33:04 Ivy Encarnacion via
>> Digitalmars-d- learn wrote:
>>
>>  A pure function cannot call any function that is not pure [...]
>
> I've read that a lot but it's not true. A pure function can call impure
> function. The restriction is, that the impure function called within the
> pure function does not depend or mutate on state existing outside of
> that function. If the called function changes local variable, it has no
> bearing on outside the scope.

D defines pure differently.

You are allowed to declare a function is pure if it takes (and possibly 
changes) mutable references. It can be called by pure functions, but 
will not be optimized in the same way one would expect traditional pure 
functions to be optimized.

We call it "weak-pure".

In D, an "impure" function is defined exactly as one that accesses 
mutable global state. Everything else can be declared pure. The one 
exception is memory allocation.

-Steve


More information about the Digitalmars-d-learn mailing list