2

In D std.regex.regex() is not pure:

import std.regex;

pure void test() // test.d(5): Error: pure function 'test' cannot call impure function 'regex'
{
    auto r = regex(r"patern123", "g");
}

Why?

Is it

A. Not enough pure keywords were thrown in.

or

B. There exists some deeper reason

dnsmkl
  • 792
  • 5
  • 17
  • 7
    Perhaps this is due to the fact that `std.regex` does some caching. – Mat Feb 17 '13 at 11:50
  • @Mat Is this an answer or just a general thought/guess? ("Perhaps" could be sign of sarcasm, but I'm not sure) – dnsmkl Feb 17 '13 at 15:00
  • I don't know D and its definition of "pureness". So it's a guess. Wasn't meant as sarcasm at all, sorry if it sounded like that. – Mat Feb 17 '13 at 15:01
  • @dnsmkl You can take a [look at code](https://github.com/D-Programming-Language/phobos/blob/master/std/regex.d#L6450) by yourself. – sigod Feb 17 '13 at 19:37

1 Answers1

3

std.regex is a module so it can't be marked as pure.

Answer to A: Marking function as pure does not make it pure. It just tells compiler that you would like it to be pure, and it will do the job if the function indeed can be made pure. If it can't be pure, compiler will raise an error. That is the case here - test() can't be pure because std.regex.regex() is not pure. Rule of thumb - a pure function can't call impure function.

Answer to B: Yes, there exist deeper reasons, and I am sure you are probably already aware of them. As a reminder read http://en.wikipedia.org/wiki/Pure_function and ask yourself does your function test() satisfy those two main rules? For this, naturally, you need to understand the semantics of the std.regex.regex() function...

Perhaps you wanted to ask Why is std.regex.regex() not pure? Mat already answered that question I think. - std.regex module does indeed maintain some cache, and it mutates it.

DejanLekic
  • 18,787
  • 4
  • 46
  • 77
  • 1
    Your answer to A is misleading, as it implies that marking a function as `pure` is a suggestion. It's not. If the function can't be `pure`, and it's marked with `pure`, then you'll get an error. – Jonathan M Davis Feb 18 '13 at 20:14
  • @DejanLekic I made mistake in the name. Question should have been "Why is std.regex.regex()" – dnsmkl Feb 18 '13 at 20:29
  • @JonathanMDavis - Good point. I thought from what I wrote it is obvious the compiler will "shout"... :) I added a sentence about compilation error to make it more clear. – DejanLekic Feb 19 '13 at 08:34