Skip to content

Instantly share code, notes, and snippets.

@karadaisy
Last active December 13, 2015 21:38
Show Gist options
  • Save karadaisy/4978663 to your computer and use it in GitHub Desktop.
Save karadaisy/4978663 to your computer and use it in GitHub Desktop.
For "Java Infinite Streams" discussion on Coursera
class Cons<T, R> {
T car;
R cdr;
Cons(T car, R cdr) {
this.car = car;
this.cdr = cdr;
}
}
interface Supplier<T> {
T apply();
}
interface Stream<T> extends Supplier<Cons<T, Stream<T>>> {
}
class Main {
static Stream<Integer> naturalsFrom(final int n) {
return new Stream<Integer>() {
public Cons<Integer, Stream<Integer>> apply() {
return new Cons<Integer, Stream<Integer>>(n, naturalsFrom(n+1));
}
};
}
public static void main(String args[]) {
Stream<Integer> st = naturalsFrom(1);
for( int ii = 0 ; ii < 10 ; ii++) {
Integer car = st.apply().car;
st = st.apply().cdr;
System.out.println(car);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment