Search code examples
pythonlambda

lambda function as argument of lambda function


I am stuck with some code in python where there are lambda functions as argument of the lambda functions. After wasting a lot of time on that code, I am trying understand this concept with a small code. I tried writing a small sample code which works fine.

def multiply(a,b):
    return a*b
def mathematical(X1, X2, X3):
    sum = X1 + X2 +X3
    return sum
multiplication = lambda x,y: multiply(x,y)
mathematical_function= lambda X1, X2: mathematical(X1, X2, multiplication(X1, X2))*2
result = mathematical_function(3,4)
print(result)

Then I tried putting the entire lambda function as argument as shown below but I am getting the ERROR. I am expecting to get the same result as for above code.

def multiply(a,b):
    return a*b
def mathematical(X1, X2, X3):
    sum = X1 + X2 +X3
    return sum
multiplication = lambda x,y: multiply(x,y)
mathematical_function= lambda X1, X2: mathematical(X1, X2, lambda x,y: multiply(x,y))*2 
result = mathematical_function(3,4)       # Problem
print(result)

The error I am getting is as below:

TypeError                                 Traceback (most recent call last)
Cell In[73], line 1
----> 1 result = mathematical_function(3,4)       # Problem
      2 print(result)

Cell In[72], line 1, in (X1, X2)
----> 1 mathematical_function= lambda X1, X2: mathematical(X1, X2, lambda x,y: multiply(x,y))*2   # Some problem

Cell In[70], line 2, in mathematical(X1, X2, X3)
      1 def mathematical(X1, X2, X3):
----> 2     sum = X1 + X2 +X3
      3     return sum

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

It would be great help if I can be helped in solving this problem since I am new to python and lambda function.


Solution

  • multiplication is a reference to a function defined as lambda x,y: multiply(x,y). You could substitute lambda x,y: multiply(x,y) for multiplication without changing your code's behavior. That's not what you did, though.

    Instead of substituting lambda x,y: multiply(x,y) for multiplication, you substituted it for multiplication(X1, X2). You took out the part where you call the function. You need to keep that part. The correct substitution would produce

    (lambda x,y: multiply(x,y))(X1, X2)
    

    not just

    lambda x,y: multiply(x,y)