Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

lambda - lazy evaluation and late binding of python?

when is lazy evaluation? (generator, if, iterator?), when is late binding? (closure, regular functions?)

    a = [1,2,3,4]
    b = [lambda y: x for x in a] 
    c = (lambda y: x for x in a) #lazy evaluation
    d = map(lambda m: lambda y:m, a) #closure
    for i in b:
        print i(None)
    # 4 4 4 4
    for i in c:
        print i(None)
    # 1 2 3 4 
    for i in d:
        print i(None)
    # 1 2 3 4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This looks like homework, so I won't just give you the answers. Here are two functions that you can step through and see how the values change.

def make_constants_like_generator():
    def make_constant(x):
        def inner(y):
            return x
        return inner
    results = []
    for i in [1, 2, 3, 4]:
        results.append(make_constant(i))
        for f in results:
            print f(None)
    return results

def make_constants_like_list():
    x = None
    results = []
    for i in [1, 2, 3, 4]:
        x = i
        def inner(y)
            return x
        results.append(inner)
        for f in results:
            print f(None)
    return results

Lazy evaluation is waiting until the last possible moment to evaluate an expression. The opposite is eager evaluation. The generator expression is lazy, it does nothing until it is iterated. The list expression is eager, as soon as it is encountered, the list is filled with values.

Early and late binding relate to how the system determines what a name refers to. All names in python are late bound. Combined with lazy evaluation that means that what a name is bound to can change before expressions that use it are evaluated

def map(func, iter):
    return (func(val) for val in iter)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...