函数式编程 - 纯函数
如果函数满足以下两个条件,则被视为纯函数 −
对于给定的输入,它总是返回相同的结果,并且其结果完全取决于传递的输入。
它没有副作用,这意味着它不会修改调用者实体的任何状态。
示例 - 纯函数
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; } }
输出
5 5
此处 sum() 是一个纯函数,因为当在不同时间传递 2 和 3 作为参数时,它始终返回 5,并且没有副作用。
示例 - 非纯函数
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; } }
输出
5.919716721877799 5.4830887819586795
此处 randomSum() 是一个非纯函数,因为它在不同时间传递 2 和 3 作为参数时会返回不同的结果,并且还会修改实例变量的状态。