From 3e5ce62f9c46ff63d3ba3d83140ed698a934a7c3 Mon Sep 17 00:00:00 2001 From: Muriithi Frederick Muriuki Date: Fri, 30 Jul 2021 10:09:56 +0300 Subject: Add module for common utilities Issue: https://github.com/genenetwork/gn-gemtext-threads/blob/main/topics/gn1-migration-to-gn2/clustering.gmi * gn3/function_helpers.py: new file Provides a new module to hold common programming utilities that are generic enough that they will find use across the entire application. The first utility function provided in this commit is the `compose` function, whose purpose, as indicated by its name, is to take a number of functions and compose them into a single function, which when called, will return the same result that would have been got had the user called the functions in a chain from right to left. --- gn3/function_helpers.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 gn3/function_helpers.py diff --git a/gn3/function_helpers.py b/gn3/function_helpers.py new file mode 100644 index 0000000..397b2da --- /dev/null +++ b/gn3/function_helpers.py @@ -0,0 +1,36 @@ +""" +This module will contain helper functions that should assist in maintaining a +mostly functional way of programming. + +It will also contain miscellaneous functions that can be used globally, and thus +do not fit well in any other module. + +FUNCTIONS: +compose: This function is used to compose multiple functions into a single + function. It passes the results of calling one function to the other until + all the functions to be composed are called. +""" +from functools import reduce + +def compose(*functions): + """Compose multiple functions into a single function. + + The utility in this function is not specific to this module, and as such, + this function can, and probably should, be moved to a more global module. + + DESCRIPTION: + Given `cfn = compose(f_1, f_2, ... f_(n-1), f_n )`, calling + `cfn(arg_1, arg_2, ..., arg_m)` should call `f_n` with the arguments passed + to `cfn` and the results of that should be passed as arguments to `f_(n-1)` + and so on until `f_1` is called with the results of the cumulative calls and + that is the result of the entire chain of calls. + + PARAMETERS: + functions: a variable argument list of function. + """ + def composed_function(*args, **kwargs): + return reduce( + lambda res, fn: fn(res), + reversed(functions[:-1]), + functions[-1](*args, **kwargs)) + return composed_function -- cgit v1.2.3