Skip to content

Instantly share code, notes, and snippets.

@bolu61
Last active February 28, 2025 17:54
Show Gist options
  • Save bolu61/ee92a143692c991cf7a44c7bf4f8a9b6 to your computer and use it in GitHub Desktop.
Save bolu61/ee92a143692c991cf7a44c7bf4f8a9b6 to your computer and use it in GitHub Desktop.
Cursed decorators
# 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
@yali-github
Copy link

Well done

@fgmehlin
Copy link

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