std.string phobos

dsimcha dsimcha at yahoo.com
Sat Sep 12 18:37:10 PDT 2009


== Quote from pc (peng2cheng2 at yahoo.com)'s article
> Is there a way to make the functions in std.string, such as replace, pure? Many
pure functions are going to  want to use these. Also, could some of them be
executable at compile time?
> For me, using D2.032, this did not compile.
> pure string replaceXX(string str){
>   return replace(str,"XX","X");
> }
> If I am missing something, help!

For a function in D to pass the compiler checks for purity, it must only call
functions that are *marked as* being pure.  If a function is not marked as pure
but is de facto pure, it won't work.  For example:

uint nPlus2(uint n) pure {
    return nPlus1( nPlus1( n));  // Not pure.
}

uint nPlus1(uint n) {
    return n + 1;
}

Many functions that are, in fact, pure, have not been annotated as such yet in
Phobos, since pure was implemented fairly recently.  If you want to help out, this
is fairly low hanging fruit.

Also, purity is very restrictive right now and is designed partly with thread
safety in mind.  A function that truly has no side effects from an observable
behavior in a single thread point of view won't necessarily pass the compiler as pure:

__gshared uint foo;

/* wasteTime() is impure even though it has no observable side
 * effects in a single thread because it still (at least
 * temporarily) manipulates global state, and thus could
 * cause problems in multithreaded code.  Furthermore, even if
 * it were thread safe, it would be hard to prove for all but
 * the simplest cases that functions like these have no
 * observable side effects.*/
void wasteTime() pure {  // Won't compile.
   foo++;
   foo--;
}



More information about the Digitalmars-d mailing list