Skip to content

Instantly share code, notes, and snippets.

@kylehovey
Created April 11, 2020 02:13
Show Gist options
  • Save kylehovey/d39d962487982d377ea8e249480d0dc5 to your computer and use it in GitHub Desktop.
Save kylehovey/d39d962487982d377ea8e249480d0dc5 to your computer and use it in GitHub Desktop.
Memoized Y Combinator
const M = f => f(f);
const Y = fn => M(
maker => x => fn(maker(maker))(x)
);
const YY = fn => {
const cache = new Map;
return M(
maker => x => {
if (!cache.has(x)) {
cache.set(x, fn(maker(maker))(x));
}
return cache.get(x);
}
);
};
const mFact = YY(
self => n => {
console.log(n);
if (n === 0) return 1;
return n * self(n - 1);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment