Last active
December 13, 2015 21:38
-
-
Save karadaisy/4978663 to your computer and use it in GitHub Desktop.
For "Java Infinite Streams" discussion on Coursera
This file contains hidden or 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
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