Skip to content

Instantly share code, notes, and snippets.

View kylehovey's full-sized avatar

Kyle Hovey kylehovey

View GitHub Profile
@kylehovey
kylehovey / memoized_y_combinator.js
Created April 11, 2020 02:13
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(
const mkWrapper = () => (
cache => f => n => n in cache
? cache[n]
: cache[n] = f(n)
)([]);
const M = f => f(f);
const Y = f => (
wrapper => M(
maker => n => wrapper(
f(M(maker))
@kylehovey
kylehovey / Convolve.js
Created February 24, 2020 04:26
Scratchpad for problem 4
const fact = n => n <= 0 ? 1 : n * fact(n-1);
const choose = (n, k) => fact(n) / (fact(n - k) * fact(k));
const mapper = predicate => n => predicate(n) ? 1 : 0;
const [isEven, isOdd] = [0,1].map(k => mapper(n => n % 2 === k));
const iverson = k => mapper(n => n === k);
const coverNegative = f => n => n < 0 ? 0 : f(n);
const conjugatePair = (a, b) => [a+b, a-b];
const round = fn => n => Math.round(fn(n));
const range = n => Array(n).fill().map((_, i) => i);
const reversed = xs => [...xs].reverse();
@kylehovey
kylehovey / Observable.cpp
Last active February 21, 2020 06:11
Observable subscription model with minimal side-effects
#include <functional>
#include <vector>
#include <iostream>
namespace Observable {
template <typename D>
using Callback = std::function<void(const D&)>;
template <typename D, typename R>
using Morphism = std::function<R(D)>;
const mapper = predicate => n => predicate(n) ? 1 : 0;
const [isEven, isOdd] = [0,1].map(k => mapper(n => n % 2 === k));
const iverson = k => mapper(n => n === k);
const range = n => Array(n).fill().map((_, i) => i);
const coverNegative = f => n => n < 0 ? 0 : f(n);
const conjugatePair = (a, b) => [a+b, a-b];
const a = coverNegative(
n => 4*b(n-1) + 2*a(n-1) + a(n-2) + iverson(0)(n)
);
function *_range(from, to) {
if (to === undefined) {
yield *_range(0, from);
return;
}
yield [ from ];
if (from >= to) return;
@kylehovey
kylehovey / eventual.js
Last active July 15, 2019 16:06
Functional version of a promise that allows you to resolve it outside of the callback in the promise constructor
/**
* Creates an intermediate value that can be resolved later.
* @return {Object} Eventual
* @return {Function} Eventual.then Acts like Promise.then for the eventual value
* @return {Function} Eventual.resolve Acts like Promise.resolve for the eventual
* @return {Function} Eventual.reject Acts like Promise.reject for the eventual
*/
const eventual = () => (
_eventual => ({
/**
@kylehovey
kylehovey / memoize.js
Created March 27, 2018 19:43
ES6 Memoize Function
function memoize(f) {
const cache = new Map;
return (...args) => {
const key = JSON.stringify(...args);
if (!cache.has(key)) {
cache.set(key, f(...args));
}