The method of implementing code reuse in functional programming languages is different from object-oriented language, which I have analyzed in the 2nd part. Object-oriented languages tend to have many data structures that can be manipulated in many ways, while functional languages have only a handful of data structures that can perform multiple operations. Object-oriented languages encourage you to create class-specific methods, and you can capture patterns that recur for later reuse. Functional languages encourage you to apply common transformations to your data structure, and use more advanced functions to customize the actions of specific instances to help you achieve reuse.
The same data structures and operations appear in all functional languages (also appearing in many frameworks that support functional programming in Java), but their names are usually different. The naming method that leads to confusion makes it difficult to convert knowledge of one language into another, even though the underlying concepts are identical.
The goal of this installment is to make this transition a little easier. This article introduces a simple problem that requires policies and iterations, in five languages (Java, Groovy, Clojure, JRuby, and Scala) and two Java functional frameworks (functional Java and totally Lazy) to implement the solution. Each language is implemented in the same way, but the details are very different.
Normal Java
The problem in this article is how to determine whether an integer is a prime number, and the prime number can only be 1 and itself. There are several algorithms for determining prime numbers (some alternative solutions can be found in part 1th); I'm going to use a solution that first determines the factor of the number and then checks whether the sum of all the factors equals the number plus 1 to determine whether the number is prime. This is not the most efficient algorithm, but my goal is to show the different implementations of common collection methods, rather than efficiency.
Listing 1 shows the normal Java version:
Listing 1. Common Java Prime number classifier
public class Primenumberclassifier {
private Integer number;
public primenumberclassifier (int number) {
this.number = number;
}
public boolean isfactor (int potential) {return number
% potential = 0;
}
Public set<integer> getfactors () {
set<integer> factors = new hashset<integer> ();
Factors.add (1);
Factors.add (number);
for (Integer i = 2; i < number; i++)
if (Isfactor (i))
factors.add (i);
return factors;
}
public int sumfactors () {
int sum = 0;
for (int i:getfactors ())
sum = i;
return sum;
}
public boolean IsPrime () {return
sumfactors () = = number + 1;
}
}
If you've read the previous functional thinking series, you'll find that the algorithm in Listing 1 is familiar to the Getfactors () method, which filters the candidate factors.