Skip to content

Instantly share code, notes, and snippets.

@Ogaday
Last active December 6, 2022 15:24
Show Gist options
  • Select an option

  • Save Ogaday/f44235c69c2933473e6faa0c303d059d to your computer and use it in GitHub Desktop.

Select an option

Save Ogaday/f44235c69c2933473e6faa0c303d059d to your computer and use it in GitHub Desktop.
Implemtation of function composition
from itertools import accumulate
from functools import reduce
from typing import Callable, Iterable, TypeVar
T = TypeVar("T")
def sequential_apply(data: T, funcs: Iterable[Callable[[T], T]]) -> Iterable[T]:
"""
Sequentially apply a list of functions to some data.
Parameters
----------
data : Any
The initial object on which to apply the functions.
funcs : Iterable of callables.
A list of functions to apply. They will be called left of right.
Returns
-------
iterator
An iterator yielding the peicewise results, including the initial data.
Example
-------
>>> funcs = [lambda x: x ** 3, lambda x: x + 5, lambda x: x * 3]
>>> data = 2
>>> list(sequential_apply(data, funcs))
[2, 8, 13, 39]
"""
yield from accumulate(funcs, lambda data, f: f(data), initial=data)
def compose(data: T, funcs: Iterable[Callable[[T], T]]) -> T:
"""
Compose a sequence of functions on some data.
Parameters
----------
data : Any
The initial object on which to compose the functions.
funcs : Iterable of callables.
A list of functions to apply. They will be called left of right.
Returns
-------
result
The result of composing the functions
Example
-------
>>> funcs = [lambda x: x ** 3, lambda x: x + 5, lambda x: x * 3]
>>> data = 2
>>> compose(data, funcs)
39
"""
return reduce(lambda data, f: f(data), funcs, data)

Function Composition

A minimal compose implementation.

Given a list of functions, apply them squentially to an argument. This is equivalent to:

funcs = [h, ..., g]
compose(x, funcs) == g(...(h(x)))

Example usage:

funcs = [lambda x: x ** 3, lambda x: x + 5, lambda x: x * 3]
data = 2
compose(data, funcs)
# ans: 39

Lint:

mypy compose.py
black --check

Test:

pytest --doctest-modules -vvv compose.py
pytest
flake8
mypy
black
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment