Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
stateMonad
const fib_cps = (n, k) => {
console.log(n);
if (n < 2) {
return k(1);
}
else {
return fib_cps(n - 1, c1 => {
return fib_cps(n - 2, c2 => {
return k(c1 + c2);
})
});
}
}
const ret_cps = fib_cps(6, x => x);
console.log('The final result is ' + ret_cps);
var sumOfNullableList = (ls, k) => {
if(ls.length){
if(ls[0] == null) {
return -1;
}
else {
return sumOfNullableList(ls.splice(1), v => k(v+ls[0]));
}
}
else {
return k(0);
}
}
console.log(sumOfNullableList([1, 2, 3, 4], x=>x));
console.log(sumOfNullableList([1, 2, null, 4], x=>x));
const factUntil = (n, limit, k) => {
if (n < 2) {
return k(1);
}
if (k(n) > limit) {
return n;
}
else {
return factUntil(n - 1, limit, (v) => k(n * v));
}
}
console.log(factUntil(5, 10, x => x));
console.log(factUntil(5, 200, x => x));
const injectState = x => s => [x, s];
const bindState = (ma, f) => s => {
const vs = ma(s);
return f(vs[0])(vs[1]);
};
const getState = s => [s, s];
const putState = newS => s => [null, newS];
const fib = n => {
console.log('fib', n);
return n < 2 ? 1 : fib(n - 1) + fib(n - 2);
};
const fibMonad = n => {
console.log('fibMonad', n);
if (n < 2) {
return bindState(getState, state => {
const newState = (state[n] = 1); // pretend this is pure
return bindState(putState(newState), _ => injectState(1));
});
} else {
return bindState(getState, state =>
bindState(
state[n - 1] ? injectState(state[n - 1]) : fibMonad(n - 1),
fib_1 =>
bindState(
state[n - 2] ? injectState(state[n - 2]) : fibMonad(n - 2),
fib_2 => {
const result = fib_1 + fib_2;
const newState = (state[n] = result); // pretend this is pure
return bindState(putState(newState), _ => injectState(result));
}
)
)
);
}
};
fib(6); // 13
// fib(20); // 10946
console.log(fibMonad(6)({})); // 13
// console.log(fibMonad(20)({})); // 10946
const fib_sps = (n, store) => {
console.log(n, JSON.stringify(store));
if (store[n]) {
return [store[n], store];
}
else if (n < 2) {
return [1, store];
}
else {
const fib_n1 = fib_sps(n - 1, store);
const fib_n2 = fib_sps(n - 2, fib_n1[1]);
const ret = fib_n1[0] + fib_n2[0];
const newStore = fib_n2[1];
newStore[n] = ret;
return [ret, newStore];
}
}
const ret_sps = fib_sps(6, {});
console.log(ret_sps[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.