Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function that takes two functions and returns the concatenated function?

I need to write a python function called 'concat' that takes any two functions as input, and returns a function, which is the concatenated function of the two input functions (i.e. it takes f1 and f2, and returns f1◦f2).

I tried this:

def concat(f1,f2):
    return f1(f2)

So for example, if f1 and f2 are:

def f1(x):
    return x+2
def f2(x):
    return x*2

then, concat(f1,f2) should return: (x*2)+2

I want to be able to use it like this:

a = concat(f1,f2)
a(5)

But I get an error:

TypeError: unsupported operand type(s) for +: 'function' and 'int'

I know I can define the function like this:

def concat(f1,f2,x): 
    return f1(f2(x))

But that is not what I want; I want to be able to create instances of the concat function, which then can be called with any x.

like image 919
AAriam Avatar asked Jun 27 '26 12:06

AAriam


2 Answers

You need to return a new "wrapper" function. One option is to use a lambda expression:

def concat(f1, f2):
    return lambda x: f1(f2(x))

DOCS: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions

like image 123
VisioN Avatar answered Jun 30 '26 01:06

VisioN


I think what you want is a closure.

def concat(f1, f2):
  def f3(x):
    return f1(f2(x))
  return f3

Functions in Python are considered first class objects. This allows them to be created and manipulated like normal variables. In this case concat is constructing a new function that composes two functions.

The second property being used here is lexical scoping. The new function retains access to the local variables where it was defined not where it is executed. This allows the returned function to be run anywhere without losing access to the composite functions.

like image 24
gph Avatar answered Jun 30 '26 02:06

gph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!