Functional Programming Concepts
- Immutability
- Expressions vs statements
- Functions
- Pure and impure functions
- refrential transparency
- Higher order function
Immutability
We cant change the variable/entity state once defined.
Why?
- Peace of mind – While debugging we are sure of one thing of what an immutable entity will hold. so less concerned about others modifying it
- Multi-threaded environment- immutable entity provides thread safety by nature.
Expressions vs statements
Expression – yields a value (return a value)
Statement- do some action (print)
Functional programming prefers using statement over expression
Functions
Function – For certain set of input we get certain output.
Types of function-
- Pure
- Impure
Pure and impure functions
Pure function – result/output purely based on input not on any other variable or environment.
Impure function-
Impure function don’t evaluate to same output for given set of inputs. they depend on other variable or environment.
Note- In general pure function are reliable – in functional programming should use Pure function as much as possible compared to impure .
Referential transparency
Applies to expressions and function (relation btw input and output).
An expression or function is called R.T. if it can be replaced with its value,without changing the algorithm. yielding the same output as when they are called without their value replacement
e.g
Violation of Referential Transparency –
- making network call – network call we can not replace with value possible to get different data because of network failure.
- updating the db
- writing to file system
Higher order function
Among other input H.O.F. takes function as input.
HOF provides us a way to abstract the part that don’t change and take the part that changes as function argument. provide code reuseabiility.