Composing functions in python

前端 未结 12 1233
北荒
北荒 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:16

    Suppose you have the following functions:

    def square(x): 
        return x**2
    
    def inc(x): 
        return x+1
    
    def half(x): 
        return x/2
    

    Define a compose function as follows:

    import functools
    
    def compose(*functions):
        return functools.reduce(lambda f, g: lambda x: g(f(x)),
                                functions,
                                lambda x: x)
    

    Usage:

    composed = compose(square, inc, inc, half)
    compose(10)
    >>> 51.0
    

    which executes the functions procedurally in the defined order:

    1. square (= 100)
    2. inc (= 101)
    3. inc (= 102)
    4. half (= 51)

    Adapted from https://mathieularose.com/function-composition-in-python/.

提交回复
热议问题