Oscalation
Oscalation

Reputation: 380

undefined variable in lambda expression

I am having trouble understanding the following function.

def make_adder(n):
    return lambda x: x + n

plus_2 = make_adder(2)

plus_2(5)
>>> 7

In this function, what does x represent and how does this not result in an error because x is undefined?

Upvotes: 0

Views: 836

Answers (4)

kmario23
kmario23

Reputation: 61365

In the line below:

plus_2 = make_adder(2)

we're binding the integer object 2 to n.

After that when plus_2 is called using the argument:

plus_2(5)

the integer object 5 would be bind to x when the lambda expression is executed.

This is the runtime execution flow. Since there is no ambiguity or errors in this whole process, the program runs just fine and outputs 7.

Now, to answer your question: the variable x represents whatever value is passed to plus_2() as per your naming.

Upvotes: 0

erip
erip

Reputation: 16935

You're defining a function which, given n, returns a function which accepts an argument x and returns x + n. This is called a higher-order function. It doesn't yield an error because you're explicitly returning another function which expects an argument.

Upvotes: 1

rdvdev2
rdvdev2

Reputation: 11

The x represents the parameter that the lambda expression receives, this is why it's before the ":".

When you do the plus_2 = make_adder(2) call, the lambda expression substitutes the n with the parameter of the function (2), so now plus_2 equals lambda x: x + 2. When you call plus_2(5) the lambda expression is evaluated, substituting the x with the function parameter (5), so the result is 5 + 2 = 7;

Upvotes: 1

williamrfry
williamrfry

Reputation: 360

Lambda functions are awesome. They allow you to define higher-order functions inline. The general format is lambda args: expression. In this case, x is the argument passed into the lambda function. Because make_adder returns a lambda function, whatever you pass into make_adder is set as n. So when you pass in make_adder(2) you get a lambda function that adds 2 to the argument (x).

Decomposing your original snippet:

def make_adder(n):
    return lambda x: x + n

plus_2 = make_adder(2)  # returns lambda x: x + 2

plus_2(5)  # executes lambda expression, x + 2 with x=5

Starting from scratch:

5 + 2  # 7

plus_two_fn = lambda x: x + 2  # Add 2 when you call plus_two_fn(x)

plus_two_fn(3)  # returns 5 (3 + 2)


def plus_num_fn(num):
    return lambda x: x + n  # Allow you to define plus "any" number


plus_one_fn = plus_num_fn(1)  # lambda x: x + 1

plus_one_fn(2)  # returns 3 (2 + 1)

Upvotes: 0

Related Questions