"Insanity is doing the same thing over and over again and expecting different results."
- Albert Einstein
We can use this insanity principle to our advantage with pure functions.
Assigning values to variables during an imperative function's execution may result in the modification of a variable in the environment in which it has run. If we run the same imperative function again, using the same input, the result may differ.
Given the results of an imperative function and given the same input, different results may be returned each time it is run. Is that not insanity?
Pure functions:
- Treat functions as first-class citizens
- Always return the same result given the same input(s)
- Have no side effects in the environment in which they run
- Do not allow an external state to affect their results
- Do not allow variable values to change over time
Two characteristics of a pure function include referential transparency and idempotence:
- Referential transparency: This is where a function call can be replaced with its corresponding value without changing the program's behavior
- Idempotence: This is where a function call can be called repeatedly and produce the same result each time
Referentially transparent programs are more easily optimized. Let's see whether we can perform optimizations using a caching technique and Go's concurrency features.