Written by @pramodk73, 7 months ago

Understanding the concept of pure functions in functional programming.


Every programmer deals with functions all the time. All the programming languages support functions. Is that the functional programming? Of course not! Using functions all over the project does not mean that you are building the system in a functional programming paradigm. Let us understand the pieces first.

What is a function?

It is important to understand a function in its raw form. A function is a set of instructions to be run based on given inputs and return a result back. Sounds familiar right? This is the basic building block of any programming language. Some programming languages call them definitions, routes, etc. but they all same.

What is functional programming?

The philosophy of functional programming is that, any function, should behave same and provide same result for the same inputs irrespective of the time it is being called. In simple terms, if there is a function sum(a, b), it should give same result, no matter how many times it is called and no matter when it is called. It boils down to, how pure a function is? Does it depend on any of the global state?

This sounds simple but gets increasingly difficult to follow this philosophy in building a complicated and heavy systems. These systems maintain multiple types of states, caches, global information.

It is hard to build any system without maintaining the state at some level. So, the idea is not to maintain the state, it is to maintain the state only at the top layers, so that the underneath layers are pure functional.

Why pure functional?

Functions which behave differently at different times is hard to predict. They become very hard to debug if there is some issue with the function. As developers, it is important to build system that is easy to debug, predictable, reliable.

No system is pure functional. It is not binary, instead it is a spectrum. It is better to be more pure functional than a complicate, state dependent system.