Skip to content

Instantly share code, notes, and snippets.

@DavidBuchanan314
Created April 27, 2022 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBuchanan314/5223f88323a736884a366a81d92e4562 to your computer and use it in GitHub Desktop.
Save DavidBuchanan314/5223f88323a736884a366a81d92e4562 to your computer and use it in GitHub Desktop.
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