Created
July 8, 2024 02:29
-
-
Save geofft/d19a002b6982a9ff97b235e16d1f24c4 to your computer and use it in GitHub Desktop.
Inadvisable adventures with the match statement
This file contains 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
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