With a friend some time ago we wanted to write our own implementation of comp() clojure function in python3. we ended up writing the following function:
def comp(*fs): """ Takes a set of functions and returns a fn that is the composition of those fns. The returned fn takes a variable number of args, applies the rightmost of fns to the args, the next fn (right-to-left) to the result, etc. """ if len(fs) == 1: return lambda *x: fs(*x) else: return lambda *x: fs(comp(*fs[1:])(*x))
In my oppinion it's still opaque and difficult to read. But it works as in:
# Checking for single argument >>> [comp(lambda x: x*10,lambda x: x+2, lambda x: x*3, lambda x: x+3)(x) for x in range(6)] [110, 140, 170, 200, 230, 260] # Checking for multiple arguments >>> a = lambda x: sum(x) >>> b = lambda x, y, z: [x*1, y*2, z*3] >>> comp(a, b)(1, 2, 3) 14
How could it be written better?