Skip to content

Instantly share code, notes, and snippets.

@infinnie
Created May 17, 2018 09:08
Show Gist options
  • Save infinnie/ebcf7c91fe83533be4f1476ac044c374 to your computer and use it in GitHub Desktop.
Save infinnie/ebcf7c91fe83533be4f1476ac044c374 to your computer and use it in GitHub Desktop.
Church Encoding in TypeScript
type Some<T> = (x: T) => T;
var add = function <T>(m: Some<Some<T>>, n: Some<Some<T>>) {
return function (f: Some<T>) {
return function (x: T) {
return m(f)(n(f)(x));
};
};
}, mul = function <T>(m: Some<Some<T>>, n: Some<Some<T>>) {
return function (f: Some<T>) {
return m(n(f));
};
}, pow = function <T>(m: Some<Some<T>>, n: Some<Some<Some<T>>>) {
return n(m);
}, pred = function (n) {
return function (f) {
return function (x) {
return n(function (g) {
return function (h) {
return h(g(f));
}
})(function (u) {
return x;
})(function (u) {
return u;
});
};
};
}, sub = function <T>(m: Some<Some<T>>, n: Some<typeof pred>): Some<Some<T>> {
return n(pred)(m);
};
var one = function (f) {
return function (x) {
return f(x);
}
};
var two = add(one, one), three = add(one, two);
var result = sub<number>(pow<number>(pow(two, three), three), three)(function (x) {
return x + 1;
})(0);
alert(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment