Monday, 28 August 2017

Functional Programming


Hello Friends, Let’s discuss about Functional Programming.

What is Functional Programming?
Functional programming is nothing just mathematical functional which perform some operations. Functional programming helps to write compact and concise code. It’s provide a very high level of abstraction although it’s reduces the code readability.

Functional programming contains the following key concept.
1.      Function as first class object
2.      Pure function.

Function as first class object
Function as first class object means we can create the instance of function similar to String, Map, List etc. Function can be passed as parameter to other functions.

Pure function
1.      A pure function have no state.
2.      It’s immutable
3.      Its return value is dependent on input variable only.
4.      Pure function is a pure mathematical expression.

Higher order functions are function which contain another function in parameter or return value is a function.

Here we are adding few example of function.

Example:

import java.util.function.BiFunction;
import java.util.function.Function;

public class Test {

      public static void main(String[] args) {
            Function<Integer,Integer> addFunc = x -> x + 1;
            System.out.println(addFunc.apply(2));
           
            BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
            System.out.println(add.apply(2, 3).intValue());
           
            BiFunction<Integer, Integer, Integer> substract = (a, b) -> a - b;
            System.out.println(substract.apply(2, 3).intValue());
           
            BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
            System.out.println(multiply.apply(2, 3).intValue());
           
            BiFunction<Integer, Integer, Integer> devide = (a, b) -> a / b;
            System.out.println(devide.apply(2, 3).intValue());
           
            Function<Integer, Function<Integer,Integer>> adder = x -> y -> x + y;
            System.out.println(adder.apply(1).apply(1));
      }
}

Output:-
3
5
-1
6
0
2


1 comment: