Skip to content

Instantly share code, notes, and snippets.

@ceving
Last active November 26, 2023 15:47
Show Gist options
  • Save ceving/6a7607bef1832ae1f68f047399e0f4ec to your computer and use it in GitHub Desktop.
Save ceving/6a7607bef1832ae1f68f047399e0f4ec to your computer and use it in GitHub Desktop.
Church Numerals JavaScript
// Implementation independant
const Z =
(inc) => (zero) => zero;
const S =
(n_times) =>
(inc) => (zero) => inc(n_times(inc)(zero));
const add2 =
(m_times) => (n_times) =>
(inc) => (zero) => m_times(inc)(n_times(inc)(zero));
const add3 =
(x) => (y) => (z) => add2(x)(add2(y)(z));
const one = S(Z);
const two = S(one);
const three = S(two);
const one_plus_two_plus_three = add3(one)(two)(three);
// Implementation for numbers
const number_zero = 0;
const number_inc = (x) => x + 1;
const to_number = (n) => n(number_inc)(number_zero);
console.log(to_number(one_plus_two_plus_three));
// Implementation for asterisks
const asterisk_zero = "";
const asterisk_inc = (x) => x + "*";
const to_asterisk = (n) => n(asterisk_inc)(asterisk_zero);
console.log(to_asterisk(one_plus_two_plus_three));
@ceving
Copy link
Author

ceving commented Nov 26, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment