Java Reference
In-Depth Information
algorithm, as follows is problematic because the loop body is updating a data structure that's
shared with the caller:
public void searchForGold(List<String> l, Stats stats){
for(String s: l){
if("gold".equals(s)){
stats.incrementFor("gold");
}
}
}
Indeed, the body of the loop has a side effect that can't be dismissed as functional style: it
mutates the state of the stats object, which is shared with other parts of the program.
For this reason, pure functional programming languages such as Haskell omit such
side-effecting operations entirely! How then are you to write programs? The theoretical answer
is that every program can be rewritten to avoid iteration by using recursion instead, which
doesn't require mutability. Using recursion lets you get rid of iteration variables that are
updated step by step. A classic school problem is calculating the factorial function (for positive
arguments) in an iterative way and in a recursive way (we assume the input is > 1), as shown in
the following two listings.
Listing 13.1. Iterative factorial
static int factorialIterative(int n) {
int r = 1;
for (int i = 1; i <= n; i++) {
r *= i;
}
return r;
}
Listing 13.2. Recursive factorial
static long factorialRecursive(long n) {
return n == 1 ? 1 : n * factorialRecursive(n-1);
}
 
Search WWH ::




Custom Search