Pure Functions
Its just a way to write methods.
In Mathematics, functions always produce the same output for a given set of inputs.
In Functional Programming world, a pure function:
- For a given input, will always produce the same output.
- should not produce any Side-effects
Have have look the function add
in following example:
Remember: We are just going to understand what a pure function can / can not do. The “logic” and the “effect/output” across all the code snippet will vary
The issue is that the function is dependent on/modifying a state which is outside its own scope.
This is an example of Side-effect
What about the following implementation of add
?
All good right?
Now let’s do a slight modification
The issue is that the original variable y
is mutable. And it will be hard to see where the y
is getting mutated if you have 100s of lines of code in between.
To solve this, make all variables immutable
Every function will always return a new variable or copy of the existing variable.
You can see the issue here, COPIES !!
Consider an example:
So just to modify a single value, we need to create a deep copy of the whole input array.
This looks insane, but in reality, Functional Programming languages implement
persistent_data_structures, which can avoid deep copies and perform efficiently.