Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing functions in python

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 compose(list):     if len(list) == 1:         return lambda x:list[0](x)     list.reverse()     final=lambda x:x     for f in list:         final=lambda x:f(final(x))     return final 

This method doesn't seems to be working, help will be appreciated.

(I'm reversing the list because this is the order of composition I want the functions to be)

like image 718
Starless Avatar asked May 24 '13 16:05

Starless


People also ask

What is composition function in Python?

Function composition is the way of combining two or more functions in such a way that the output of one function becomes the input of the second function and so on.

What are composing functions?

In Maths, the composition of a function is an operation where two functions say f and g generate a new function say h in such a way that h(x) = g(f(x)). It means here function g is applied to the function of x. So, basically, a function is applied to the result of another function.

How do you write a function in Python?

Basic Syntax for Defining a Function in Python In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.

What are the 4 types of functions in Python?

Moreover, we will study the different types of functions in Python: Python built-in functions, Python recursion function, Python lambda function, and Python user-defined functions with their syntax and examples.


1 Answers

The easiest approach would be first to write a composition of 2 functions:

def compose2(f, g):     return lambda *a, **kw: f(g(*a, **kw)) 

And then use reduce to compose more functions:

import functools  def compose(*fs):     return functools.reduce(compose2, fs) 

Or you can use some library, which already contains compose function.

like image 95
Suor Avatar answered Oct 09 '22 03:10

Suor