pure-ifying my code

Jonathan M Davis jmdavisProg at gmx.com
Sun Nov 17 05:02:22 PST 2013


On Sunday, November 17, 2013 13:53:52 Philippe Sigaud wrote:
> >> But `popFront()` changes an internal state with visible, external
> >> effects: it changes `front` return value and in the end, it will
> >> affect `empty` return value.
> >> So no, I don't consider `popFront` to be pure.
> > 
> > None of that matters for pure. _All_ that matters for pure is that the
> > function does not access global, mutable state - so no mutable global or
> > static variables. _Strong_ purity requires more, but you're not going to
> > get that with a member function anyway, unless it's immutable, which is
> > almost never the case.
> > 
> > If you're trying to think about functional purity when dealing with pure,
> > you're definitely going to misunderstand it, because functional purity
> > really has very little to do with D's pure. At this point, pure is all
> > about indicating that the function does not access anything mutable that
> > you don't pass to it.
> 
> I know the difference between functional purity and D purity. It's
> just I consider the range internal state to *be* something mutable
> that I don't pass to the member.
> 
> I never considered that code like this:
> 
> auto a = range.front();
> auto temp = a;
> range.popFront(); // pure popFront()?
> a = range.front();
> assert(temp != a); // pure popFront() modified range.front() value!
> 
> could be authorized. Maybe that's because, until now, I only *read*
> about D purity and never tried to use it in my code.

If you just think about pure as meaning that the function doesn't access any 
mutable global state, then you'll have a much better grasp of pure. 
Essentially, it restricts the function to accessing what's passed to it 
directly and to global constants which can't possibly have changed their value 
once they were set, even through other references to them. As such, pure has 
nothing to do with mutation. Though it is true that it can seem a bit weird 
with member functions if you forget the fact that they're being passed the 
this pointer/reference as one of their arguments, which is the case with 
popFront. So, that's probably what was throwing you off.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list