Hello folks....!!!
Today let us look at the function composition concept in Python.
Function Composition
It is a way of combining two or more functions such that the result of one function is passed to the next function. The syntax is
variable_name=compose(func1,func2)
where
f(),g()
are functions. 'x' is the parameter passed by the user to the function
g(), the result of
g(x)
is passed to
f().
Let us look at the difference between with and without function composition.
The above code snippet is without function composition. First the func1(3) is called and the result is stored in 'a', which is passed as an argument to the next function dec().
Here the compose(f,g) takes two arguments, f and g which are functions. If the syntax is f(g(x)), then the outer function must be passed first and then the inner function. Here we have to find the cube of a number first and decrement it by 1.
If you want to compose more than two functions, then compose the functions in pairs in appropriate order. Now let us assume that we need to add one more functionality to the above snippet. Thus we need to square a number, decrement it by 1 and 10 to it.
The functions are executed from the last. Thus the flow is :
Let us look at the difference between with and without function composition.
The above code snippet is without function composition. First the func1(3) is called and the result is stored in 'a', which is passed as an argument to the next function dec().
Here the compose(f,g) takes two arguments, f and g which are functions. If the syntax is f(g(x)), then the outer function must be passed first and then the inner function. Here we have to find the cube of a number first and decrement it by 1.
If you want to compose more than two functions, then compose the functions in pairs in appropriate order. Now let us assume that we need to add one more functionality to the above snippet. Thus we need to square a number, decrement it by 1 and 10 to it.
The functions are executed from the last. Thus the flow is :
{ func1 (x) → dec ( func1 (x) → inc ( dec ( func1 (x) ) ) }
Next Topic👉
Comments
Post a Comment