Skip to content

Instantly share code, notes, and snippets.

@SpandanBG SpandanBG/memoize.js

Last active Jul 30, 2019
Embed
What would you like to do?
Challenge 1 from https://bartoszmilewski.com/2014/11/24/types-and-functions/ => A memoize function takes a function f and returns a function that takes a value x. When x is passed the first time it returns a function that would take the next x. If the x passed was passed before it would compute f(x) and return the result. The solution here is do…
const head = x => _ => x;
const tail = _ => y => y;
const arr = x => xs => f => f(x)(xs);
const none = () => null;
const memoize = f => {
const bind = xs => _x => y => {
if (xs === none) {
return bind(arr({arg: y, ret: f(y)})(_x))(none);
}
if (xs(head).arg === y) {
return xs(head).ret;
}
return bind(xs(tail))(arr(xs(head))(_x))(y);
};
return bind(none)(none);
};
const fib = n => {
if (n <= 0) {
return 1;
}
return n * fib(n - 1);
};
((/* main */) => {
let memid = memoize(fib);
memid = memid(3);
memid = memid(4);
memid = memid(1);
memid = memid(2);
console.log(memid(4))
})()
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.