Created
April 27, 2022 01:14
-
-
Save DavidBuchanan314/5223f88323a736884a366a81d92e4562 to your computer and use it in GitHub Desktop.
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
from dataclasses import dataclass | |
def lambda_match_wrapper(instance, _locals): | |
return type("MatchWrapper", (), { | |
"__getattribute__": (lambda self, name: | |
type("EqWrapper", (), { | |
"__eq__": (lambda self, o: | |
eval(o, None, dict(_locals, self=instance)) )})() | |
if name == "_lambda" else | |
instance.__getattribute__(name) )})() | |
class Tree(): pass | |
@dataclass | |
class Leaf(Tree): | |
v: int | |
@dataclass | |
class Node(Tree): | |
left: Tree | |
right: Tree | |
def exists_leaf(tree: Tree, test): | |
match lambda_match_wrapper(tree, locals()): | |
case Leaf(_lambda="test(self.v)") \ | |
| Node(_lambda= | |
"exists_leaf(self.left, test)" | |
| "exists_leaf(self.right, test)"): | |
return True | |
return False | |
def has_even_leaf(tree: Tree): | |
return exists_leaf(tree, lambda n: n % 2 == 0) | |
print(has_even_leaf(Leaf(0))) | |
print(has_even_leaf(Node(Leaf(3), Node(Leaf(7), Leaf(6))))) | |
print(has_even_leaf(Node(Leaf(3), Node(Node(Leaf(5), Leaf(27)), Leaf(3))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment