Saturday, October 23, 2010

Infinite sequences in Java

One of the interesting features in a lot of functional languages is lazily evaluated infinite sequences. Java lacks any explicit syntax for creating sequences, however the Iterator interface combined with generics lets us implement just such a feature, though it's obviously not as clean or succinct as in some languages.

As an example, here's an implementation of an "infinite" sequence of 64-bit integers.

package blog;

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class Sequence
implements Iterable<long> {

private long value;

public Sequence(long start) {
value=start;
}

public Sequence() {
this(0L);
}

public Iterator<long> iterator() {
return new LazyIterator();
}

public List<long> take(int toTake) {
ArrayList<long> retVal =
new ArrayList<long>(toTake);
for(int i = 0; i < toTake; ++i) {

public boolean hasNext() {
/* Always return true, because this
sequence is "infinite" */
return true;
}

public Long next() {
// store where we are
long retVal = value;
// Move on to the next value
++value;
// auto-boxing will turn it into a Long
return retVal;
}

public void remove() {
throw new UnsupportedOperationException();
}
}
}
This technique is also useful for parsing documents or in other situations where generating the entire list would either take too long or too much memory.

No comments: