Question about pure functions

Jonathan M Davis jmdavisProg at gmx.com
Mon Sep 16 09:53:07 PDT 2013


On Monday, September 16, 2013 10:08:22 anonymous wrote:
> Mark all parameters const to get a strong pure function. For
> "this" const goes on the method:

That's not actually enough. At present, in order for a function to be 
considered strongly pure, all of its parameters must be either immutable or 
implicitly convertible to pure (including the this reference). A const 
reference type is neither.

In principle, a function could be considered strongly pure if its parameters 
were const but its arguments were immutable, but the compiler isn't that smart 
about it at this point. The parameters themselves must be immutable or 
implicitly convertible to immutable.

So, at present, for a member function to be considered strongly pure, it must 
be an immutable member function, not const. In theory it could be const if the 
object itself were immutable, but again, the compiler isn't that smart about 
it at this point. In either case, the actual object would have to be 
immutable, which is not the case in most code.

And if you make the member functions immutable, they can only be called by 
immutable objects, forcing you to either duplicate your functions or make it 
so that your class can only be constructed as immutable.

pure member functions are useful, because they guarantee that the function is 
not accessing global mutable state, and because it makes it so that they can 
be called from strongly pure functions, but in general, pure member functions 
can't be strongly pure and therefore can't be optimized.

If you want to see how many times a pure function is being called, then put a
call to writeln inside of a debug {} block inside of it and compile with
-debug, since debug blocks are not checked for purity (since they're for
debugging). It should then print out every time it's being called, which should
allow you to see whether multiple calls with the same arguments within an
expression are actually being optimized out (though you might have to compile
with -O for the compiler to do the optimizations - I don't know).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list