Skip to content

Instantly share code, notes, and snippets.

@jsyeo
Created October 17, 2012 19:10
Show Gist options
  • Save jsyeo/3907476 to your computer and use it in GitHub Desktop.
Save jsyeo/3907476 to your computer and use it in GitHub Desktop.
Fibonacci Continuation Passing Style in Java
interface Cont {
int k(int v);
}
public class Fib {
public static void main(String args[]){
String res = "";
int arr[] = {0,1,2,3,4,5,6,7,8,10};
for (int elem:arr) {
res += (fib(elem,
new Cont() {
public int k(int v) {
return v;
}})) + ", ";
}
System.out.println("First 10 fibonacci numbers: "+res);
}
static int fib(final int n, final Cont cont) {
if (n <= 1) {
return cont.k(1);
} else {
return fib(n-1,
new Cont(){
public int k(final int ret){
return fib(n-2, new Cont(){
public int k(int ret2){
return cont.k(ret+ret2);
}
});
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment