Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a pure function?

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.

like image 872
user3395918 Avatar asked Mar 08 '14 11:03

user3395918


1 Answers

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.

like image 185
juanchopanza Avatar answered Oct 11 '22 04:10

juanchopanza