regexex, enforce and purity

monarch_dodra monarchdodra at gmail.com
Sun Sep 9 12:04:58 PDT 2012


Given this little program testing regexs, I decided to replace 
one of the example's assert with an enforce:

--------
import std.regex;
import std.exception;
void main()
{
     auto m = match("hello world", regex("world"));
     assert(m);
     enforce(m); // <-- HERE
     enforce(cast(bool)m);
     enforce(!m.empty);
}
--------

I get the compile errors:
src\phobos\std\exception.d(356): Error: pure function 'enforce' 
cannot call impure function '~this'
src\phobos\std\exception.d(358): Error: pure function 'enforce' 
cannot call impure function 'opCast'

While I understand the problem at play, I have a few doubts:
1)Why the difference between assert and enforce? Shouldn't both 
have the same restraints?
2)What exactly does purity mean for a *member* function?
3)And shouldn't RegexMatch's .opCast (and .empty) should be 
qualified as pure?

...

I did some digging while typing, and was about to suggest that 
the problem could be solved if enforce was required to take a 
boolean as an argument (makes sense), forcing the cast *outside* 
of the enforce. However, it would appear that enforce returns its 
value, the goal (probably) being to make this legal:

auto bar = enforce(foo());

The return value is enforced and passed to bar in a 1-liner.

BUT... assert doesn't do that. THAT is the original source of the 
difference in behavior.

So I'll rephrase my 1):
Why the difference in behavior regarding the return value? Is it 
just historical/no real reason, or is there something for me to 
learn here?



More information about the Digitalmars-d-learn mailing list