After a stumbled upon this question I thought about how I would define a pure function. I have two rules to accept a function as pure which somewhat differ from the definition cited in the top answer. I'm interested to know if my view is correct or not. My "2 rules" are:
To clarify the second point, by local public state
I mostly mean public
class members. Local means that the state is strongly associated with the function and is exclusive to it (ie. not some global variables).
My reasoning for using that definition is that it is just a more expanded view (perhaps too specific to CS) on the term arguments
, as I see local public state
being only a different interface for passing function arguments.
Is this definition acceptable or is the inclusion of a class context destroys the "prunes" of the function?
Edit: As an example for what I mean consider the following class (C++).
class Foo
{
public:
int Number;
int foo(int v) { return Number + v; }
}
Considering that an instance function call is actually the following call:
foo(&this, 123)
How is this different from passing the public data (Number) via a struct?
struct Foo
{
int Number;
}
foo(Foo { 1 }, 123);
No, that "or the same local public program state" is not in the pure method definition everyone else agrees with.
A pure function computes a value based on the input parameters and the input parameters alone, and does not, beyond returning the computed value, produce any observable side effects.
I advice you to take a look at the Wikipedia page on Pure function as it shows some examples.
--
Also note that "no observable side effects" does not mean "no side effects whatsoever", but the gray area overlapping those two generally only include runtime-specific side effects that you have no control over and generally do not observe.
This also includes state such as "there is enough memory to allocate the memory needed".