Composing functions in python

前端 未结 12 1258
北荒
北荒 2020-11-27 03:56

I have an array of functions and I\'m trying to produce one function which consists of the composition of the elements in my array. My approach is:

def compo         


        
12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 04:14

    I prefer this one due to readability/simplicity

    from functools import reduce
    
    def compose(*fs):
       apply = lambda arg, f: f(arg)
       composition = lambda x: reduce(apply, [x, *fs])
       return composition
    

    the pipe = compose(a, b, c) will first apply a, then b and then c.

    With regard to maintainability (an debugging) I think actually this one is the easiest to use:

    def compose(*fs):
        def composition(x):
            for f in fs:
                x = f(x)
            return x
        return composition
    

提交回复
热议问题