Anonymous function: Difference between revisions

Content deleted Content added
Article needs more on what anonymous functions would be useful for
Uses: Added closures
Line 42:
 
which clearly has by sorted by length of the strings.
 
===Closures===
{{main|Closure (computer science)}}
 
Closures are functions evaluated in an environment containing [[bound variable]]s. The following example binds the variable "threshold" in an anonymous function that compares the input to the threshold.
 
<source lang="python">
def comp(threshold):
return lambda x: x < threshold
</source>
 
This can be used as a sort of generator of comparison functions:
 
<source lang="python">
a = comp(10)
b = comp(20)
 
print a(9), a(10), a(20), a(21)
True False False False
 
print b(9), b(10), a(20), b(21)
True True False False
</source>
 
It would clearly be very impractical to create a function for every possible comparison function and may be too inconvenient to keep the threshold around for further use. Regardless of the reason why a closure is used the anonymous function is what the contains the functionality that does the comparing.
 
==List of languages==