Skip to content

Instantly share code, notes, and snippets.

@koru1130
Last active August 2, 2020 08:24
Show Gist options
  • Save koru1130/290156918ea0dd1f9e51115ced257b65 to your computer and use it in GitHub Desktop.
Save koru1130/290156918ea0dd1f9e51115ced257b65 to your computer and use it in GitHub Desktop.
Fibonacci |> CPS |> defunctionalization |> TCO |> defunctionalization
//const lam1_fun = (n, k) => x => fib_cps((n-2), lam2_fun(x, k))
const lam1_def = (n, k) => ({
tag: 'lam1',
n: n,
k: k
})
//const lam2_fun = (x, k) => y => k(x+y)
const lam2_def = (x, k) => ({
tag: 'lam2',
x: x,
k: k
})
const id_def = ({
tag: 'id'
})
const apply_thunk = (f, x) => ({
thunk_tag: 'apply',
f: f,
x: x
})
const apply = (f, x) =>{
switch (f.tag) {
case 'lam1':
return fib_thunk((f.n-2), lam2_def(x, f.k));
case 'lam2':
return apply_thunk(f.k, f.x + x);
case 'id':
return x;
}
}
const fib_thunk = (n, k) => ({
thunk_tag: 'fib',
n: n,
k: k
})
const fib_def = (n, k) => {
switch(n){
case 0:
return apply_thunk(k, 0);
case 1:
return apply_thunk(k, 1);
default:
return fib_thunk((n-1), lam1_def(n, k));
}
}
const eval = t => {
switch(t.thunk_tag){
case 'apply':
return apply(t.f, t.x);
case 'fib':
return fib_def(t.n, t.k);
}
}
const tco_def = (t) => {
while(t.thunk_tag) {
//console.log(JSON.stringify(t))
t = eval(t);
}
return t;
};
console.log(tco_def(fib_def(5, id_def)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment