Pure Functions – Category Theory

What is a pure function? This is more abstract and not specific to C++. I ran across this term while watching a video from Bartosz Milewski at C++ Russia, 2015 on Categories. I felt that this little bit about a pure function can help programmers and when I code, I try to use it frequently.

  1. A pure function has no side effects. Think “functional language”. Or a const function in C++. It doesn’t modify any state.
  2. When called with the same arguments, it always returns the same result. (Referential Transparency)
  3. It can be memoized. Because it doesn’t depend on shared state, you can precompute the results. The example he uses is the Fibonacci sequence. A function that compute the Fibonacci sequence can be precomputed and cached off into a table.
  4. Because there’s no side effects of a pure function and they don’t modify a shared state, it’s easier to move function calls around.

Comments are closed.