spekk.transformations.common.compose

Contents

spekk.transformations.common.compose#

spekk.transformations.common.compose(x, *wrapping_functions)[source]#

Apply each f in fs to x.

Let’s say we have some functions:

>>> f = lambda x: x+1
>>> g = lambda x: x*2
>>> h = lambda x: x**2

We can use compose() to apply each function in order:

>>> compose(1, f, g, h)  # ((1 + 1) * 2) ** 2 = 16
16

This would be the same as calling:

>>> h(g(f(1)))  # ((1 + 1) * 2) ** 2 = 16
16

In situations with a lot of nested function calls, compose() may be more readable. Also notice that when using compose, functions are evaluated in the order that they are passed in (left-to-right), while with the nested function calls, the functions are evaluated in the reverse order (right-to-left).

compose() can also be used to build up a function from smaller function transformations:

>>> wrap_f_double = lambda f: (lambda x: 2*f(x))
>>> wrap_f_square = lambda f: (lambda x: f(x)**2)
>>> f = compose(
...   lambda x: x+1,
...   wrap_f_double,
...   wrap_f_square,
... )
>>> f(1)  # ((1 + 1) * 2) ** 2 = 16
16