[phobos] [D-Programming-Language/phobos] 4f28db: not really pure

Steve Schveighoffer schveiguy at yahoo.com
Mon Jun 27 03:51:52 PDT 2011


----- Original Message -----

> From: Walter Bright <walter at digitalmars.com>
> 
> 
> 
> On 6/25/2011 8:25 PM, Jonathan M Davis wrote:
>>  On 2011-06-25 20:23, Walter Bright wrote:
>>>  On 6/25/2011 8:01 PM, Jonathan M Davis wrote:
>>>>  If they're not really pure, they shouldn't compile with 
> pure.
>>>  They won't in the upcoming checkin.
>>> 
>>>>     Also, not being
>>>> 
>>>>  able to use opAssign in pure functions could be rather annoying. 
> Why
>>>>  doesn't that work?
>>>  Pure functions cannot mutate data through pointers passed to them.
>>  Weakly pure functions are supposed to be able to.
>> 
>> 
> 
> The compiler wasn't checking this at all. It's possible we can loosen 
> things up 
> after we understand the issues better, but we should start with being very 
> conservative about what purity means.

Don is probably the best to explain it, since he formalized the notion of weak pure,  but I wholeheartedly agree with Jonathan, member functions that access or mutate mutable members can and should be pure, as long as they don't access or mutate shared or global data.

If that isn't true, then the whole notion of weak purity that allows pure functions to be useful is out the window.  I.e. pure functions will be reserved to the likes of std.math.sin, and nobody will mark any major functions pure.

I thought weak purity had already been scrutinized, accepted, and purposefully added to the compiler?  Were you not part of that discussion (I thought you were)?  Does this reverse that decision?  If so, I think it is the wrong move.  Weak purity made pure functions not only useful, but actually pleasant to work with.

To recap weak purity, a pure function is one that does not access mutable or const data that is shared or global, and it can only call pure functions.
A Strong-pure function is a pure function whose parameters and return value are all immutable or implicitly convertible to immutable.

The compiler can only make pure-related optimizations on strong-pure functions.  However, since weak-pure functions are still pure, strong-pure functions can call them.

For instance, a useful idiom would be for a weak-pure function to sort an array in place.  Without weak-purity, one has to re-implement sorting an array in every pure function they need it for, or write a functional-style sort (not a very easy or efficient thing).

In other words, weak purity makes pure functions written in an imperative style able to be modular.  Without it, you have to resort to functional style, or mixin everything into your local scope.

-Steve



More information about the phobos mailing list