Last active
February 28, 2025 17:54
-
-
Save bolu61/ee92a143692c991cf7a44c7bf4f8a9b6 to your computer and use it in GitHub Desktop.
Cursed decorators
This file contains hidden or 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
# Chapter 1: immediate evaluation with optional composition | |
@lambda f: not f() | |
def true() -> bool: | |
return False | |
assert true == True # ??? | |
# Chapter 2: single line composition | |
from functools import partial | |
@partial(partial, lambda f, *a, **k: not f(*a, **k)) | |
def inv(x: bool) -> bool: | |
return x | |
assert inv(true) == (not true) # ??? | |
# Chapter 3: [something useful maybe](https://stackoverflow.com/a/24047214) | |
from functools import reduce | |
@partial(partial, lambda f, *fs: reduce(f, fs)) | |
def compose(f, g): | |
def composed(*a, **k): | |
return f(g(*a, **k)) | |
return composed | |
@partial(compose, lambda x: not x, lambda x: not x) | |
def ident(x: bool) -> bool: | |
return x | |
assert ident(true) == true | |
# Epilogue: recursive comprehension? | |
@partial(compose, list) | |
def postorder(tree: list[int], n: int = 0): | |
if n >= len(tree): | |
return | |
yield from postorder(tree, 2 * n + 1) | |
yield from postorder(tree, 2 * n + 2) | |
yield n |
That's horribly beautiful, or beautifully horrible... not sure which one...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well done