Created
January 26, 2024 19:20
-
-
Save peterroelants/592bdb02def87ce89b587454f4b44ab1 to your computer and use it in GitHub Desktop.
Python Function composition
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
from functools import partial | |
from typing import Protocol | |
class Callable(Protocol): | |
def __call__(self, *args, **kwargs): | |
... | |
class Params: | |
"""Parameters to be passed to a function""" | |
def __init__(self, *args, **kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
def __rlshift__(self, other: Callable) -> "Function": | |
return Function(partial(other, *self.args, **self.kwargs)) | |
class Function: | |
"""Composable Function""" | |
def __init__(self, f: Callable): | |
self.f = f | |
def __call__(self, *args, **kwargs): | |
return self.f(*args, **kwargs) | |
def __mul__(self, other: Callable) -> "Function": | |
return Function(lambda x: self(other(x))) | |
def __rmul__(self, other: Callable) -> "Function": | |
return Function(lambda x: other(self(x))) | |
class Call: | |
"""Application Operator""" | |
def __call__(self, f: Callable): | |
return f() | |
@classmethod | |
def __ror__(cls, other: Callable): | |
return other() | |
c = Call() | |
P = Params | |
F = Function | |
fa = F(lambda x: x + "a") | |
fb = F(lambda x: x + "b") | |
print(f"{c(fa << P('x'))=}") | |
print(f"{fa << P('x') | c=}") | |
print(f"{fa * fb << P('x') | c=}") | |
""" | |
- https://docs.python.org/3/reference/datamodel.html | |
- https://docs.python.org/3/reference/expressions.html#operator-precedence | |
- https://en.wikipedia.org/wiki/Function_composition | |
- https://www.sfu.ca/~tjd/383summer2019/haskell_comp_and_app_lhs.html | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment