Reputation: 547
I've been given this function. It returns the function pair
that it also returns the function f
I think. That is the part that tricks me, I don't know what f(a, b)
is and how to use it.
def cons(a, b):
def pair(f):
return f(a, b)
return pair
Upvotes: 1
Views: 758
Reputation: 81
Well if you could share the complete question then we might be able to help you better. Meanwhile what I can tell you here is that in the return of pair(f) the program is calling a function f which takes two arguments a and b. This function f(a,b) is called and then its value will be returned to pair(f).
But the point to note here is that in pair function we already have a local variable f, so when we will try to call the function f(a,b) it will give us UnboundedLocalVariable error. Therefore, we will need to change the name of this function from f to something else.
Upvotes: 0
Reputation: 22963
. . . I don't know what
f(a, b)
is and how to use it.
f(a, b)
is simply a function call. All the code you provided does is define a function that returns a function. The function returned from the first function, itself returns a function. I assume the way it would be used is perhaps something like:
>>> cons(1, 2)(lambda x, y: x + y)
3
>>>
The above code would be equivalent to:
>>> pair_func = cons(1, 2) # return the `pair` function defined in `cons`
>>> f = lambda x, y: x + y
>>> pair_func(f) # apply the `f` function to the arguments passed into `cons`.
3
>>>
It might also help to note that the pair
function defined in this case, is what's know as a closure. Essentially, a closure is a function which has access to local variables from an enclosing function's scope, after the function has finished execution. In your specific case, cons
is the enclosing function, pair
is the closure, and a
and b
are the variables the closure is accessing.
Upvotes: 1
Reputation: 20571
To help you understand what is going on, consider the following example:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def my_func(a, b):
return a + b
# cons returns a function that takes a function arg and calls it with args (a, b),
# in this case (1, 3). Here a, b are considered "closured" variables.
apply_func = cons(1, 3)
print apply_func(my_func) # prints 4
Upvotes: 3
Reputation: 19362
Lets analyse this from inside out:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
The innermost level is return f(a, b)
- that obviously calls function f
with arguments (a, b)
and returns whatever the result of that is.
The next level is pair
:
def pair(f):
return f(a, b)
Function pair
takes a function as an argument, calls that function with two arguments (a, b)
and returns the result. For example:
def plus(x, y):
return x + y
a = 7
b = 8
pair(plus) # returns 15
The outermost level is cons
- it constructs function pair which has arbitrary a
and b
and returns that version of pair. E.g.
pair_2_3 = cons(2,3)
pair_2_3(plus) # returns 5, because it calls plus(2, 3)
Upvotes: 1