14

I found this quote:

  1. Make predicts pure functions.

Predicate purity: A predicate is a function object that returns a yes/no answer, typically as a bool value. A function is pure in the mathematical sense if its results depend only on its arguments (note that this use of "pure" has nothing to do with pure virtual functions).

Don't allow predicates to hold or access state that affects the result of their operator(), including both member and global state. Prefer to make operator() a const member function for predicatse (see Item 15).

What is a pure function as referred to in this statement and can someone provide examples? Thanks in advance.

user3395918
  • 195
  • 5
  • 5
    The quote provides a definition, so it's not entirely clear which part you find confusing? – NPE Mar 08 '14 at 11:45

3 Answers3

20

This is a pure function:

int foo(int n)
{
  return n*2;
}

The result of calling it depends only on its argument.

This is not a pure function:

int i = 42;

int bar(int n)
{
  ++i;
  return n*i;
}

The returned value depends on things other than the parameter.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
9

Function is pure if:

  1. It has no semantically observable side effects
  2. Always returns the same result given the same input

So the function can still have a state, but it should not be observable. For example:

int foo(std::vector<int> v) {

  static std::vector<int> tmp;
  tmp.resize(v.size);

  std::transform(v.begin(), v.end(), tmp.begin(), [](int a) {return a * a;});
  return std::accumulate(tmp.begin(), tmp.end(), 0);
}

function foo has a state (static vector), however it is not semantically observable, thus its pure. Its a stupid function, but it should show the point.

Blaz Bratanic
  • 2,279
  • 12
  • 17
0

Pure functions do not have side effects and always return a result which is determined by its input values only and the return value is always the same for the same input values.

They are very easy to test.

An example of a pure function would be a reducer within Redux (ideally they should be pure functions). Examples for side-effects are for example http requests.

And some code example for a pure function:

int multiplyByTwo(int n)
{
  return n * 2;
}
Ini
  • 548
  • 7
  • 19