I wrote a function and I'd like to find out if it is an implementation of some functional programming pattern or construct. I'd like to find out the name of this pattern or construct (if it exists)?
I have a function which takes a list of functions and does this to them:
wrap(fn1, fn2, fn3, fn4) # returns partial(fn4, partial(fn3, partial(fn2, fn1)))
There are strong similarities to compose, reduce, and other fp metaprogramming constructs, since the functions are being arranged together and returned as one function.
It also has strong similarities to decorators and Python context managers since it provides a way to encapsulate pre and post execution behaviors in one function. Which was the impetus for writing this function. I wanted the ability that context managers provide, but I wanted to be able to have it defined in one function, and to be able to layer function after function on top.
For clarity I've added the implementation:
_wrap = partial(reduce, lambda inner, outer: partial(outer, inner)) def wrap(fns): fns = tuple(fns) if len(fns)==1: return fns return lambda *a, **kw: _wrap(iter(fns))(*a, **kw)
and an example:
def fn_one(fn, *a, **kw): print "entered one" response = fn(*a, **kw) print "exited one" return response def fn_two(fn, *a, **kw): print "entered two" response = fn(*a, **kw) print "exited two" return response def zero(): print "zero" wrapped_zero = wrap((zero, fn_one, fn_two)) wrapped_zero() # returns entered two, entered one, zero, exited one, exited two