Typical Recursion Example (hanoi problem)
public void move(int n, String strFrom, String strTemp, String strTo) {
if (n == 1) {
show(1, strFrom, strTo);
} else {
move(n - 1, strFrom, strTo, strTemp);
move(n - 1, strTemp, strFrom, strTo);
}
}
Then I come cross the term recursion and tail recursion in Erlang.
%% recursion
sum([H|T]) ->
H + sum(T);
sum([]) ->
0.
%% tail recurion
sum(X) ->
sum(X, 0).
sum([H|T], Acc) ->
sum(T, H + Acc);
sum([], Acc) ->
Acc.
What is A Tail Call?
A tail call is a fancy term that refers to a situation in which a method or function call is the last instruction inside of another method or function.
Recursion Code with Java.
/**
* sum from 1 to n. recursion
* @param i
* @return sum
*/
public int recur_head(int i){
if(i==1)
return 1;
else
return i+recur_head(i-1);
}
Tail Recursion Code with Java.
/***
* sum from 1 to n. tail recursion
* @param i
* @param total
* @return
*/
public int recur_tail(int i, int total){
if (i == 1)
return 1+total;
return recur_tail(i-1, total +i);
}
See the class with
javap -c
public class Recur {
public Recur();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public int recur_head(int);
Code:
0: iload_1
1: iconst_1
2: if_icmpne 7
5: iconst_1
6: ireturn
7: iload_1
8: aload_0
9: iload_1
10: iconst_1
11: isub
12: invokevirtual #2 // Method recur_head:(I)I
15: iadd
16: ireturn
public int recur_tail(int, int);
Code:
0: iload_1
1: iconst_1
2: if_icmpne 9
5: iload_2
6: iconst_1
7: iadd
8: ireturn
9: aload_0
10: iload_1
11: iconst_1
12: isub
13: iload_2
14: iload_1
15: iadd
16: invokevirtual #3 // Method recur_tail:(II)I
19: ireturn
}
for Java Developer
Java programmers tend to avoid recursion through the use of loops.
int factorial(int n) {
int result = 1;
for (int t=n; t > 1; t--)
result *= t;
return result;
}
Reference
http://www.drdobbs.com/jvm/tail-call-optimization-and-java/240167044