Skip to content

Instantly share code, notes, and snippets.

@peterroelants
Created January 26, 2024 19:20
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 peterroelants/592bdb02def87ce89b587454f4b44ab1 to your computer and use it in GitHub Desktop.
Save peterroelants/592bdb02def87ce89b587454f4b44ab1 to your computer and use it in GitHub Desktop.
Python Function composition
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