JAVA8 實現遞迴函式
阿新 • • 發佈:2019-02-07
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)); }
最後執行結果如圖所示