FP Core concepts: Pure functions & Side-Effects
What are pure functions?
Published in
5 min readMay 29, 2018
A pure function is
- Referential transparency, meaning they consistently yield the same results given the same input, irrespective of where and when they are invoked. That is, function evaluation depends less — ideally, not at all — on the side effects of mutable state.
- Produce no side-effects
Advantages of pure functions
- Simpler to reason about
- Easier to combine
- Easier to test
- Easier to debug
- Easier concurrency
What are side-effects?
Side-effect is some extra work done when calling a function which changes something in the world around it. Lets take an example to understand it better.
Problems with side-effects
- Source of complexity
- Cannot be tested
- Cannot be composed
Lets create a pure-function i.e function without side-effect first.
func squareValue(_ x: Int) -> Int {return x * x}squareValue(3)// Now we can test thisassert(squareValue(2) == 4, “Failure”)assert(squareValue(3) == 9, “Failure”)