Skip to content

Instantly share code, notes, and snippets.

@qingant
Created February 8, 2022 10:53
Show Gist options
  • Save qingant/ac9cab0743ced210b0d0e8dec10a1c25 to your computer and use it in GitHub Desktop.
Save qingant/ac9cab0743ced210b0d0e8dec10a1c25 to your computer and use it in GitHub Desktop.
Peano Natural Numbers in Python
'''
Peano Natural Numbers ( https://en.wikipedia.org/wiki/Peano_axioms )
'''
class Nat(object):
def __init__(self, prev=None):
self.prev = prev
def __eq__(self, other) -> bool:
if self.prev is None and other.prev is None:
return True
elif self.prev is None and other.prev is not None:
return False
elif other.prev is None and self.prev is not None:
return False
return self.prev == other.prev
def __add__(self, other):
if other == Nat():
return self
elif other.prev == Nat():
return Nat(self)
return Nat(self) + other.prev
def __sub__(self, other):
if other == Nat():
return self
elif other.prev == Nat():
if self.prev is None:
raise Exception('Not allowed in Natural Number Set')
return self.prev
else:
return self.prev - other.prev
def _to_repr(self):
if self.prev is None:
return 0
else:
return self.prev._to_repr() + 1
def __repr__(self):
return f'Nat({self._to_repr()})'
Zero = Nat()
AnotherZero = Nat()
One = Nat(Zero)
AnotherOne = Nat(AnotherZero)
Two = Nat(AnotherOne)
print('0 == 0', Zero == Zero, Zero == AnotherZero)
print('1 != 0', Zero == One, AnotherZero == One, AnotherZero == AnotherOne)
print('1 == 1', One == One, One == AnotherOne, AnotherOne == One)
print('Zero, One', Zero, AnotherZero, One, AnotherOne)
print(Two + Two, Two + Zero, Two + One + Two)
print(Two + Two - AnotherOne)
print(One - Two)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment