Java Reference
In-Depth Information
LazyList<Integer> numbers = from(2);
int two = primes(numbers).head();
int three = primes(numbers).tail().head();
int five = primes(numbers).tail().tail().head();
System.out.println(two + " " + three + " " + five);
This will print “2 3 5,” which are the first three prime numbers. You can now have some fun; for
example, you could print all the prime numbers (the program will run infinitely by writing a
printAll method, which iteratively prints the head and tail of a list:
static <T> void printAll(MyList<T> list){
while (!list.isEmpty()){
System.out.println(list.head());
list = list.tail();
}
}
printAll(primes(from(2)));
This being a functional programming chapter, we should explain that you could do this neatly
recursively:
static <T> void printAll(MyList<T> list){
if (list.isEmpty())
return;
System.out.println(list.head());
printAll(list.tail());
}
But this program wouldn't run infinitely; sadly it would eventually fail due to stack overflow
because Java doesn't support tail call elimination, as discussed in chapter 13 .
Whew!
So you've built a whole lot of technology: lazy lists and functions using them just to define a data
structure containing all the primes. Why? What's the practical use? Well, you've seen how to
place functions inside data structures (because Java 8 allows you to), and these functions can be
used to create parts of the data structure on demand instead of when the structure is created.
This might be useful if you're writing a game-playing program, perhaps for chess; you can have a
data structure that notionally represents the whole tree of possible moves (far too big to
 
Search WWH ::




Custom Search