How to open a closure in python?
The function cons
takes two arguments, a
and b
, and returns a function that takes one argument, f
. The returned function is a closure, since it contains references to a
and b
which would otherwise be out of scope when cons
returns.
The returned function takes a function argument, calls it with a
and b
, and returns the result.
For example, if you do:
func = cons(6, 8)
Then you can do:
def g(a, b):
return a
func(g)
This will return 6
. Similarly, if you define g
to return b
, then func
would return 8
.
you can try:
pair = cons(6, 8)
def first(pair):
return pair(lambda x, y: x)
def second(pair):
return pair(lambda x, y: y)
print(first(pair))
print(second(pair))
# ouput:
# 6
# 8