Skip to content

Instantly share code, notes, and snippets.

@SpandanBG
Last active October 20, 2020 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpandanBG/c2cf6a08703be3c716e963c0048997ef to your computer and use it in GitHub Desktop.
Save SpandanBG/c2cf6a08703be3c716e963c0048997ef to your computer and use it in GitHub Desktop.
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 memorize = 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 = memorize(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