FP Core concepts: Pure functions & Side-Effects

What are pure functions?

Balraj Singh
techtron

--

A pure function is

  1. 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.
  2. Produce no side-effects

Advantages of pure functions

  1. Simpler to reason about
  2. Easier to combine
  3. Easier to test
  4. Easier to debug
  5. 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

  1. Source of complexity
  2. Cannot be tested
  3. 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”)

--

--

Balraj Singh
techtron

Software Engineer, Blogger, Tea Lover and Learner