Function - What is the difference between a 39closure39 and a 39lambda39

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.

And now that we re here, how do they differ from a regular function?

Answers

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal

Another important point - func will continue to close over anotherfunc s environment even when it s no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambda s - they are two different (although related) concepts.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils