From 42b43f8d46fe0c25703de914a687127726ece35e Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Mon, 15 Jan 2024 17:49:14 +0300 Subject: Extract common functional tools to separate package. --- functional_tools/__init__.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 functional_tools/__init__.py (limited to 'functional_tools') diff --git a/functional_tools/__init__.py b/functional_tools/__init__.py new file mode 100644 index 0000000..057bd9a --- /dev/null +++ b/functional_tools/__init__.py @@ -0,0 +1,33 @@ +"""Tools to help with a more functional way of doing things.""" +from typing import Iterable +from functools import reduce + +def take(iterable: Iterable, num: int) -> list: + """Take at most `num` items from `iterable`.""" + iterator = iter(iterable) + items = [] + try: + for i in range(0, num): # pylint: disable=[unused-variable] + items.append(next(iterator)) + + return items + except StopIteration: + return items + +def chain(value, *functions): + """ + Flatten nested expressions + + Inspired by, and approximates, Clojure's `->`. + + Useful to rewrite nested expressions like func3(a, b, func2(c, func1(d e))) + into arguably flatter expressions like: + chain( + d, + partial(func1, e=val1), + partial(func2, c=val2), + partial(func3, a=val3, b=val3)) + + This can probably be improved. + """ + return reduce(lambda result, func: func(result), functions, value) -- cgit v1.2.3