Implicit conversions through purity

Jonathan M Davis jmdavisProg at gmx.com
Wed Apr 16 02:37:23 PDT 2014


On Tuesday, April 15, 2014 18:01:59 bearophile wrote:
> Steve Teale:
> > Since this is D-Learn, I can be indignant, and say that D needs
> > to get its act together, and have a clean definition of 'pure'.
> > What you describe is not only undocumented, but also far too
> > complicated - pure weak nothrow dontpiss kissmyass @never, and
> > so on if the direction continues.
> 
> There is a nice article on D purity that I suggest you to read.
> Unfortunately I don't remember the link.

http://klickverbot.at/blog/2012/05/purity-in-d/

The key thing to understand about pure though is that _all_ it guarantees is 
that the function cannot access mutable, global variables or call any other 
functions which are not pure. The only variables that it can access which are 
either global and guaranteed to never change their values after initialization 
(which generally means that they're immutable) and the ones which are passed 
in directly to the function or which can be accessed via the variables that 
are passed in.

So, really, pure has _nothing_ to do with mathematical purity. It's just 
protecting against access to global variables. Now, that restriction allows a 
number of other things to be derived from that, which allows us to do cool 
stuff - including optimizing functions which _are_ pure in the mathematical 
sense. The most basic distinction would be what is typically called weak or 
strong purity, where strongly pure functions have immutable parameters (and 
thus multiple calls with the same arguments can be optimized to a single 
call), and weakly pure functions are pure functions which aren't strongly 
pure. Strongly pure functions generally can be optimized, whereas weakly pure 
functions cannot, but the actual distinctions can get more complicated than 
that, so even talking about weak vs strong purity isn't actually clear enough.

So, it's certainly true that things get a bit complicated when discussing what 
can be inferred due to the fact that a function is pure. And it doesn't always 
come down to strong vs weak purity either. So, I wouldn't expect very many 
people to understand under what circumstances the compiler is able to do 
certain things with a pure function, and that's not necessarily a good thing.

However, the key thing to understand with pure itself is that all it means is 
that the function can't access global, mutable state or call other functions 
which aren't pure. Pretty much everything else about it is essentially either 
a compiler optimization based on that information or an implicit type 
conversion which is made legal based on that information.

Regardless, I'd advise reading David's blog post on the matter, which I linked 
to above.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list