Last active
February 26, 2023 20:30
-
-
Save mcwitt/a13efa4b424ed5427c266082ec7b520e to your computer and use it in GitHub Desktop.
Fixed-point combinator in Python
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 functools import partial | |
def fix1(f, x): | |
return f(partial(fix1, f), x) | |
fact = lambda f, n: 1 if n <= 1 else n * f(n - 1) | |
def fix(f): | |
return f(lambda: fix(f)) | |
fact0 = lambda f: lambda n: 1 if n <= 1 else n * f()(n - 1) | |
attrs = lambda f: { | |
"foo": lambda: "foo", | |
"bar": lambda: "bar", | |
"foobar": lambda: f()["foo"]() + f()["bar"](), | |
"foobarfoobar": lambda: f()["foobar"]() + f()["foobar"](), | |
} | |
from typing import Callable, Dict, TypeVar | |
K = TypeVar("K") | |
V = TypeVar("V") | |
def evals(f: Callable[[V], Dict[K, Callable[[], V]]]) -> Dict[K, V]: | |
return {k: f() for k, f in fix(f).items()} | |
from functools import cache | |
import time | |
@cache | |
def expensive(): | |
time.sleep(2) | |
return 42 | |
r = lambda f: { | |
"foo": lambda: expensive(), | |
"bar": lambda: f()["foo"]() + expensive(), | |
"baz": lambda: f()["bar"]() + expensive(), | |
"qux": lambda: f()["baz"]() + expensive(), | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment