Last active
October 20, 2023 21:17
-
-
Save archena/6701388 to your computer and use it in GitHub Desktop.
Generators in Java via Iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
class GeneratorTest { | |
public static void main(String[] args) { | |
/** | |
* A generator for Fibonacci numbers | |
*/ | |
Generator<Integer> g = new Generator<>(new Sequencer<Integer>() { | |
private int a = 1, b = 1; | |
public Integer get() { | |
final int t = a; | |
a = b; | |
b += t; | |
return t; | |
} | |
}); | |
/** | |
* Output 10 values | |
*/ | |
for(int i = 0; i < 10; ++i) { | |
System.out.println(g.next()); | |
} | |
} | |
} | |
/** | |
* A function with no parameters | |
*/ | |
interface Sequencer<T> { | |
T get(); | |
} | |
/** | |
* A generator represents an unbounded sequence. | |
* By using an iterator we can have a lazily-evaluated infinite sequence. | |
*/ | |
final class Generator<T> implements Iterator<T> { | |
private final Sequencer<T> sequence; | |
public Generator(Sequencer<T> sequence) { | |
this.sequence = sequence; | |
} | |
public boolean hasNext() { | |
return true; | |
} | |
public T next() { | |
return sequence.get(); | |
} | |
public void remove() { | |
sequence.get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment