-
-
Save kana-sama/ce6d17341fa2c61d9422a0a9d368f9c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const B = f => g => x => f(g(x)); | |
const K = a => b => a; | |
const I = a => a; | |
const toPair = p => p(a => b => ({ first: a, second: b })); | |
const toNumber = n => n(x => x + 1)(0); | |
const toArray = l => l(x => xs => [x, ...xs])([]); | |
const toBoolean = b => b(true)(false); | |
const pair = a => b => f => f(a)(b); | |
const first = p => p(K); | |
const second = p => p(K(I)); | |
const _true = K; | |
const _false = K(I); | |
const succ = n => s => z => s(n(s)(z)); | |
const add = n => m => s => z => n(s)(m(s)(z)); | |
const mul = n => m => s => z => n(m(s))(z); | |
const _0 = s => z => z; | |
const _1 = succ(_0); | |
const _2 = succ(_1); | |
const _3 = succ(_2); | |
const _4 = mul(_2)(_2); | |
const pred = n => s => z => second(n(p => pair(s(first(p)))(first(p)))(pair(z)(z))); | |
const isZero = n => n(K(_false))(_true); | |
console.log(toNumber(pred(_4))); // 3 | |
console.log(toBoolean(isZero(_0))); // true | |
console.log(toBoolean(isZero(_1))); // false | |
console.log(toNumber(add(_1)(_3))); // 4 | |
console.log(toNumber(mul(_4)(_4))); // 16 | |
const nil = fold => init => init; | |
const cons = x => xs => fold => init => fold(x)(xs(fold)(init)); | |
const append = x => l => l(cons)(cons(x)(nil)); | |
const map = f => l => l(B(cons)(f))(nil); | |
const list = cons(_1)(cons(_2)(cons(_3)(nil))); | |
const list2 = append(_4)(list); | |
console.log(toArray(map(toNumber)(list2))); // [1, 2, 3, 4] | |
const range = n => second(n(p => pair(succ(first(p)))(append(first(p))(second(p))))(pair(_0)(nil))); | |
console.log(toArray(map(toNumber)(range(_4)))); // [0, 1, 2, 3] | |
const factorial = n => map(succ)(range(n))(mul)(_1); | |
console.log(toNumber(factorial(succ(_4)))); // 120 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment