Tuesday, March 22, 2016

Python - function chaining

Implementing chaining of functions. This is reverse of python inbuilt map() function.

map() function works on each element of an iterable by applying the given function and returns the resultant list.

>>> map(int, ['1', '2', '3'])
[1, 2, 3]

In contrast the below implemented function would execute a chain of functions on a given argument.

function implementation:-
>>> fchain = lambda fnlist, argument: reduce( lambda x, fn: fn(x), [ argument ] + fnlist )

Example for running this:-

>>> def double(x):  
...   return x*2
...
>>> def triple(x):
...   return x*3

>>> fchain([double, triple, double, double], 10)

240