Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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