Skip to content

Instantly share code, notes, and snippets.

@michelesr
Created January 15, 2025 22:41
Show Gist options
  • Select an option

  • Save michelesr/07871225d0e33595183417e7f8fe0f1a to your computer and use it in GitHub Desktop.

Select an option

Save michelesr/07871225d0e33595183417e7f8fe0f1a to your computer and use it in GitHub Desktop.
Boolean logic and church numerals in python
# Boolean logic
def true(a, _):
return a
def false(_, b):
return b
def not_f(b):
return b(false, true)
def and_f(a, b):
return a(b, false)
def or_f(a, b):
return a(true, b)
# Church numerals
def zero(_):
return lambda x: x
def one(f):
return lambda x: f(x)
def two(f):
return lambda x: f(f(x))
def three(f):
return lambda x: f(f(f(x)))
def add_1(n):
return lambda f: lambda x: f(n(f)(x))
def add(m, n):
return lambda f: lambda x: m(f)(n(f)(x))
def mul(m, n):
return lambda f: lambda x: m(n(f))(x)
def to_int(cn):
return cn(lambda x: x + 1)(0)
if __name__ == "__main__":
assert not_f(true) == false
assert not_f(false) == true
assert or_f(false, false) == false
assert or_f(false, true) == true
assert or_f(true, false) == true
assert or_f(true, true) == true
assert and_f(false, false) == false
assert and_f(false, true) == false
assert and_f(true, false) == false
assert and_f(true, true) == true
assert to_int(add_1(three)) == 4
assert to_int(add(two, three)) == 5
assert to_int(mul(two, three)) == 6
assert to_int(mul(zero, three)) == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment