1. 程式人生 > >JAVA8 實現遞迴函式

JAVA8 實現遞迴函式

JAVA8引入的lambda表示式是為了支援函數語言程式設計,很多傳統的程式設計風格都可以用lambda來進行實現,今天講一下關於遞迴函式的實現。

  • 傳統方式實現遞迴

以階乘為例,實現階乘的遞迴程式碼比較簡單,如下所示

	private static int factorial(int x){
		if(x == 1 || x==0)
			return 1;
		return x*factorial(x-1);
	}
呼叫這個遞迴函式,就能實現階乘功能。
  • lambda實現遞迴
lmabda是利用介面實現的,所以首先需要有一個介面來接收lambda表示式的函式,這裡我們使用UnaryOperator<T>介面來說明問題,UnaryOperator<T>介面是JAVA8內建的函式式介面,UnaryOperator<T>介面接收一個T型別引數,並且返回一個T型別引數,如果遞迴函式的輸入和輸出有其他的特性,那麼需要選擇其他的函式式介面,JAVA8提供了一些,還可以自己實現函式式介面。按照傳統的方式,我們來實現遞迴的邏輯,卻發現會有編譯錯誤。原因是此時的fact實際上是一個域而不是一個函式,這個域在這一行被完整的定義,在沒有定義完成之前,沒辦法引用自身。此時可以通過this引用來指向fact。


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));
	
}

最後執行結果如圖所示