views:

97

answers:

4

Please note: by a "pure" function, I don't mean "pure virtual"
I'm referring to this

If a function "reads" some global state, does that automatically render it impure? or does it depend on other factors?

If it automatically renders it impure, please explain why.

If it depends on other factors, please explain what are they.

+6  A: 

A "pure" function is a function whose result depends only on its input arguments. If it reads anything else, it is not a pure function.

Greg Hewgill
A: 

Pure functions are required to construct pure expressions. Constant expressions are pure by definition.

So, if your global 'state' doesn't change you are fine.

Also see referential transparency:

A more subtle example is that of a function that uses a global variable (or a dynamically scoped variable, or a lexical closure) to help it compute its results. Since this variable is not passed as a parameter but can be altered, the results of subsequent calls to the function can differ even if the parameters are identical. (In pure functional programming, destructive assignment is not allowed; thus a function that uses global (or dynamically scoped) variables is still referentially transparent, since these variables cannot change.)

dirkgently
+2  A: 

In certain specialized instances, yes. For example, if you had a global cache of already-computed values that was only read and written by your function, it would still be mathematically pure, in the sense that the output only depended on the inputs, but it wouldn't be pure in the strictest sense. For example:

static int cache[256] = {0};
int compute_something(uint8_t input)
{
    if(cache[input] == 0)
        cache[input] = (perform expensive computation on input that won't return 0);
    return cache[input];
}

In this case, so long as no other function touches the global cache, it's still a mathematically pure function, even though it technically depends on external global state. However, this state is just a performance optimization -- it would still perform the same computation without it, just more slowly.

Adam Rosenfield
A: 

In Haskell for instance, you can create an endless list of random numbers on the impure side, and pass that list to your pure function. The implementation will generate the next number your pure function is using only when it needs it, but the function is still pure.