Lambda calling itself to the definition of lambda

I am doing a difficult hack in Python, it is a problem when you mix for + lambda + * args (don't do this at home children), boring details may be omitted, a unique solution that I found to solve the problem The task is to pass lambda -object in an independent lambda as follows:

for ...
    lambda x=x, *y: foo(x, y, <selflambda>)

Is this possible? Thanks a lot.

+3
source share
5 answers

While your question is really strange, try something like:

>>> import functools
>>> f = lambda selflambda, x=x, *y: foo(x, y, selflambda)
>>> f = functools.partial(f, f)
+4
source

You are looking for a fixed-point combinator , as well as a Z combinator, for which Wikipedia provides this Python implementation:

Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))

Z , , , .

, :

Z(lambda f: lambda x=x, *y: foo(x, y, f))
+8

,

bar=lambda x=x, *y: foo(x, y, bar)

0

- .

def mkfun(foo, x):
    f = lambda x=x, *y: foo(x, y, f)
    return f

for ...:
    ...mkfun(foo, x)...

, gnibbler, for.

EDIT: . !

def foo(x, y, bar):
    print x
    if y:
        bar()  # call the lambda. it should just print x again.

# --- gnibbler answer
funs = []
for x in range(5):
    bar=lambda x=x, *y: foo(x, y, bar)  # What does bar refer to?
    funs.append(bar)
funs[2](2, True)  # prints 2 4 -- oops! Where did the 4 come from?

# --- this answer
def mkfun(x, foo):
    bar = lambda x=x, *y: foo(x, y, bar)  # different bar variable each time
    return bar
funs = []
for x in range(5):
    funs.append(mkfun(x, foo))
funs[2](2, True)  # prints 2 2
0

, lambda.

lambda: ,

def: ,

:

for ...
    def selflambda(x=x, *y):
        return foo(x, y, selflambda)
    ...

, ? selflambda. , , , ?

EDIT: Well, Jason Orendorf pointed out that this will not work, because every time through the loop the name selflambdawill bounce to a new function, so all function objects will try to call the latest version of the function. I will leave this for educational value, and not because it is a good answer.

0
source

Source: https://habr.com/ru/post/1727691/


All Articles