Functional Programming With Java 简明教程
Functional Programming with Java - Recursion
递归是在函数中调用相同函数,直到满足特定条件。它有助于将大问题分解成小问题。递归还使代码更具可读性和表现力。
Recursion is calling a same function in a function until certain condition are met. It helps in breaking big problem into smaller ones. Recursion also makes code more readable and expressive.
Imperative vs Recursive
以下示例展示了使用这两种技术计算自然数的总和。
Following examples shows the calculation of sum of natural numbers using both the techniques.
public class FunctionTester {
public static void main(String[] args) {
System.out.println("Sum using imperative way. Sum(5) : " + sum(5));
System.out.println("Sum using recursive way. Sum(5) : " + sumRecursive(5));
}
private static int sum(int n){
int result = 0;
for(int i = 1; i <= n; i++){
result = result + i;
}
return result;
}
private static int sumRecursive(int n){
if(n == 1){
return 1;
}else{
return n + sumRecursive(n-1);
}
}
}
Tail Recursion
尾递归是指递归方法调用应位于结尾。以下示例展示了使用尾递归打印数字序列。
Tail recursion says that recursive method call should be at the end. Following examples shows the printing of a number series using tail recursion.
public class FunctionTester {
public static void main(String[] args) {
printUsingTailRecursion(5);
}
public static void printUsingTailRecursion(int n){
if(n == 0)
return;
else
System.out.println(n);
printUsingTailRecursion(n-1);
}
}
Head Recursion
头递归是指递归方法调用应位于代码的开头。以下示例展示了使用头递归打印数字序列。
Head recursion says that recursive method call should be in the beginning of the code. Following examples shows the printing of a number series using head recursion.
public class FunctionTester {
public static void main(String[] args) {
printUsingHeadRecursion(5);
}
public static void printUsingHeadRecursion(int n){
if(n == 0)
return;
else
printUsingHeadRecursion(n-1);
System.out.println(n);
}
}