Functional programming is programming in which we try to bind each and everything in pure mathematical functions style. It is a declarative programming style. Its main focus is on “what to solve” in an imperative style whereas, in other types of programming, the main focus is “how to solve. It does not use statements but uses expressions. A statement is executed to assign values to variables whereas expression is evaluated to produce a value.
Pure functions have two main properties.
a) They always produce the same output for the same arguments.
b) They have no setbacks i.e they modify any argument global variables or output something.
Its main property is immutability. The pure functions only return the actual result. They are deterministic.
Programs that used functional programming are easy to debug because pure functions have no side effects. Pure functions also make it easier to write parallel applications. When the code is written in a functional programming style, a smart compiler can do many things. Tt can parallelize the instructions and also wait to evaluate results when needing them also memorize the results because the results never change as long as the input doesn’t change.
Example of Pure Function
mul(a, b) // mul is a function taking a and b as arguments
return a + b // mul is returning mul of a and b without changing them
There is no concept of “for” or “while” loop in functional languages. Iteration in functional languages can be done through recursion. Recursive functions continuously call themselves, until it reaches the base statement case.
example of the recursive function:
if (n <= 1)
return fun1(n - 1) + fun1(n - 2);
Variables that are defined once do not change their value throughout the program. Functional programs do not follow the concept of assignment statements. We always define new variables if we have to store some value. It reduces any chances of side effects because at any point in execution any variable can be replaced. The state of any variable is constant at any instant.
y = y + 1 // this changes the value assigned to the variable y.
// So the expression is not referentially transparent.
First-class functions are also called as the first-class variable that variables can be passed to functions as a parameter and can be returned from functions or can be stored in data structures. Higher-order functions can also return functions and are the functions that take other functions as arguments.
We can’t modify a variable in functional programming after it’s been initialized. We can create new variables – but we can’t modify existing variables, and this helps to maintain state throughout the runtime of a program. Once we create a variable and set its value, we can have full confidence knowing that the value of that variable will never change.