Created
July 20, 2025 07:08
-
-
Save tanduong/865c34f89124928e1a50b0ac9a21f4da to your computer and use it in GitHub Desktop.
Demonstrate lamda calculus with javascript
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
/* ───────── λ‑CALCULUS EXAMPLE ────────── */ | |
/* Booleans | |
TRUE ≡ λa.λb. a | |
FALSE ≡ λa.λb. b */ | |
const TRUE = a => b => a; // λa.λb.a | |
const FALSE = a => b => b; // λa.λb.b | |
/* IF ≡ λc.λt.λe. c t e */ | |
const IF = c => t => e => c(t)(e); // λc.λt.λe.c t e | |
/* Zero test | |
IS_ZERO ≡ λn. n (λ_. FALSE) TRUE | |
(apply FALSE n times to TRUE) */ | |
const IS_ZERO = n => n(_ => FALSE)(TRUE); | |
/* Predecessor | |
PRED ≡ λn. λf.λx. n (λg.λh. h (g f)) (λu.x) (λu.u) | |
– encodes a pair‑trick counter */ | |
const PRED = | |
n => f => x => | |
n(g => h => h(g(f)))(u => x)(u => u); | |
/* Multiplication | |
MUL ≡ λm.λn. λf.λx. m (n f) x */ | |
const MUL = m => n => f => x => m(n(f))(x); | |
/* Addition (derived just for nice literals below) | |
ADD ≡ λm.λn. λf.λx. m f (n f x) */ | |
const ADD = m => n => f => x => m(f)(n(f)(x)); | |
/* Numerals | |
ZERO ≡ λf.λx. x | |
ONE ≡ λf.λx. f x | |
TWO ≡ λf.λx. f (f x) | |
… etc. Here we build 2‑5 with ADD for brevity */ | |
const ZERO = f => x => x; // λf.λx.x | |
const ONE = f => x => f(x); // λf.λx.f x | |
const TWO = ADD(ONE)(ONE); // λf.λx.f (f x) | |
const THREE = ADD(TWO)(ONE); // … | |
const FOUR = ADD(THREE)(ONE); | |
const FIVE = ADD(FOUR)(ONE); | |
/* toInt : Church → JS Int (n ≡ λf.λx. fⁿ x) */ | |
const toInt = n => n(k => k + 1)(0); | |
/* Y‑combinator (strict JS variant) | |
Y ≡ λF.(λx.F (λy. x x y)) (λx.F (λy. x x y)) */ | |
const Y = F => (x => F(y => x(x)(y)))(x => F(y => x(x)(y))); | |
/* Factorial | |
fact ≡ Y (λrec. λn. | |
IF (IS_ZERO n) | |
(ONE) | |
(MUL n (rec (PRED n)))) */ | |
const FACT = Y(rec => n => { | |
const thunk = | |
IF(IS_ZERO(n)) | |
(() => ONE) // 0! ≡ 1 | |
(() => MUL(n)(rec(PRED(n)))); // n! ≡ n * (n‑1)! | |
return thunk(); // force the chosen branch | |
}); | |
/* Demo : 4! */ | |
const resultChurch = FACT(FOUR); // a Church numeral | |
console.log("4! =", toInt(resultChurch)); // → 4! = 24 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment