diff options
author | Frederick Muriuki Muriithi | 2024-01-15 17:49:14 +0300 |
---|---|---|
committer | Frederick Muriuki Muriithi | 2024-01-15 17:49:14 +0300 |
commit | 42b43f8d46fe0c25703de914a687127726ece35e (patch) | |
tree | f30490a689be720969a1a57cd3bd92e9abf68739 /functional_tools | |
parent | ef6da7313f96390b9fecb126f9b7e9beb1afe034 (diff) | |
download | gn-uploader-42b43f8d46fe0c25703de914a687127726ece35e.tar.gz |
Extract common functional tools to separate package.
Diffstat (limited to 'functional_tools')
-rw-r--r-- | functional_tools/__init__.py | 33 |
1 files changed, 33 insertions, 0 deletions
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) |