Functional Programming With Java 简明教程

Functional Programming - Pure Function

如果函数满足以下两个条件,则该函数被视为纯函数:

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

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

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

Example- Pure Function

public class FunctionTester {
   public 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

这里 sum() 是一个纯函数,因为它在以不同时间传递 2 和 3 作为参数时始终返回 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

public class FunctionTester {
   private static double valueUsed = 0.0;
   public 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

这里 randomSum() 是一个不纯函数,因为它在以不同时间传递 2 和 3 作为参数时返回不同的结果,并修改实例变量的状态。

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.