Pure Functions

Posted in: main (1 min read)
Note: This page is new / WIP.

A pure function is a function which:

  1. is referentially transparent - it will always return the same output for the same input

  2. have no side effects - it doesn't affect the outside world

Example (JavaScript)

function calc(num) {
  return num + 42
}

This function is reasonably pure - it always returns the same output for the same input and it produces no side effects.

How about this:

let factor = 2
function calc(num) {
  return factor * (num + 42)
}

If the factor would never change, this function could also be considered pure. And const declaration can help us with that:

const factor = 2

OK, that's better. But that only works because numbers are immutable in JS.

What if we have something like this:

cost o = {factor: 42}
function calc(num) {
  return o.factor * (num + 42)
}

Objects are mutable in Javascript, and to make matters worse, their prototypes are also mutable. In such a language, it's very hard to guarantee anything.

Things like immutable.js (implementation of persistent data structures) can help us to get closer, but keep in mind that in a practical sense, purity is a spectrum, not a binary thing.

Benefits

Both the referential transparency and the lack of side effects make pure functions much easier to reason about.

Other benefits: better composability, unit testing, parallelization, easier debugging, etc.

Challenges

The biggest challenge with writing pure functions is separating/isolating the side effects from the pure code. See Functional core, imperative shell for more on this topic.

See also:


Comments, suggestions, and questions are welcome.