Skip to content

Instantly share code, notes, and snippets.

@geofft
Created July 8, 2024 02:29
Show Gist options
  • Save geofft/d19a002b6982a9ff97b235e16d1f24c4 to your computer and use it in GitHub Desktop.
Save geofft/d19a002b6982a9ff97b235e16d1f24c4 to your computer and use it in GitHub Desktop.
Inadvisable adventures with the match statement
import operator
class Bigger(type):
def __new__(cls, op):
self = super().__new__(cls, "spam", (), {})
self.op = op
return self
def __instancecheck__(self, instance):
match instance:
case (a, b):
return self.op(a, b)
return False
a_is_bigger = Bigger(operator.gt)
b_is_bigger = Bigger(operator.lt)
def gcd(a: int, b: int) -> int:
while True:
match (a, b):
case (r, 0) | (0, r):
return r
case a_is_bigger():
a %= b
case b_is_bigger():
b %= a
case _:
return a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment