Friday, August 17, 2018

Functional programming


What is Functional Programming ?


Functional programming is a way of programming in which we bind everything in pure mathematical functions style. It follows declarative type of programming. It mainly focus on 
“what to solve” while imperative style main focus is “how to solve”. 
It is mainly based on expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables.

functional  programming Languages example: JavaScript, Haskell, Scala, Erlang, Lisp,OCaml, Common Lisp, Racket, ML, Clojure etc. 

Concepts


Functions are First-Class and can be Higher-Order

First class functions are represented as first class variable. The first class variables can be used in functions as parameter, can be returned from functions or stored in data structures. Higher order functions are the functions that take other functions as arguments and they can also return functions.

Pure functions

Pure functions have properties like .
1. it always produce the same output for same arguments .
2. it have no side-effects i.e. it don't modify any argument or global variables or output something.
3. it also make it easier to write parallel/concurrent applications.

Recursion

“for” or “while” loop are used in functional languages. Iteration is implemented through recursion in functional languages. Recursive function repeatedly call itself, until it reaches the base case.
eg: fib(n)
    if (n <= 1)
        return 1;
    else
        return fib(n - 1) + fib(n - 2);

Variables are Immutable

We can’t modify a variable after initialization in functional programming. We create new variables, we don’t modify existing variables, and it helps to maintain state in the runtime of  program. Once we declare a variable and assign its value, we can be sure that the value of that variable will never alter. 

Referential transparency

it does not have assignment statements, it means, the value of a variable in a functional program will not change after it is defined. it eliminates any chance of side effects as any variable can be replaced with its actual value at any point of execution. So, we can say functional programs are referentially transparent.

No comments:

Post a Comment