JAVA8引入的lambda表达式是为了支持函数式编程,很多传统的编程风格都可以用lambda来进行实现,今天讲一下关于递归函数的实现。
- 传统方式实现递归
以阶乘为例,实现阶乘的递归代码比较简单,如下所示
private static int factorial(int x){
if(x == 1 || x==0)
return 1;
return x*factorial(x-1);
}
调用这个递归函数,就能实现阶乘功能。
- lambda实现递归
private UnaryOperator<Integer> fact = x->((x==1 || x==0)? 1 : x * this.fact.apply(x-1));
静态成员变量,则需要使用类名来引用fact。整个代码如下所示
import java.util.function.UnaryOperator;
public class TestRecursion {
public static void main(String[] args) {
System.out.println(factorial(5));
System.out.println(new TestRecursion().fact.apply(5));
System.out.println(factStatic.apply(5));
}
private static int factorial(int x){
if(x == 1 || x==0)
return 1;
return x*factorial(x-1);
}
private UnaryOperator<Integer> fact = x->((x==1 || x==0)? 1 : x * this.fact.apply(x-1));
private static UnaryOperator<Integer> factStatic = x->((x==1 || x==0)? 1 : x * TestRecursion.factStatic.apply(x-1));
}
最后运行结果如图所示