English 中文(简体)
Pure Functions
  • 时间:2024-12-22

Functional Programming - Pure Function


Previous Page Next Page  

A function is considered as Pure Function if it fulfils the following two conditions −

    It always returns the same result for the given inputs and its results purely depends upon the inputs passed.

    It has no side effects means it is not modifying any state of the caller entity.

Example- Pure Function

pubpc class FunctionTester {    
   pubpc static void main(String[] args) {
      int result = sum(2,3);
      System.out.println(result);
  
      result = sum(2,3);
      System.out.println(result);
   }
   static int sum(int a, int b){
      return a + b;
   }
}

Output

5
5

Here sum() is a pure function as it always return 5 when passed 2 and 3 as parameters at different times and has no side effects.

Example- Impure Function

pubpc class FunctionTester {
   private static double valueUsed = 0.0; 
   pubpc static void main(String[] args) {
      double result = randomSum(2.0,3.0);
      System.out.println(result);
      result = randomSum(2.0,3.0);
      System.out.println(result);
   }
   
   static double randomSum(double a, double b){
      valueUsed = Math.random();       
      return valueUsed + a + b;
   }
}

Output

5.919716721877799
5.4830887819586795

Here randomSum() is an impure function as it return different results when passed 2 and 3 as parameters at different times and modifies state of instance variable as well.

Advertisements