Anonymous function: Difference between revisions

Content deleted Content added
Article needs more on what anonymous functions would be useful for
Line 2:
 
Some [[object-oriented]] programming languages have [[anonymous class]]es, which are a similar concept. [[Java (programming language)|Java]] is such a language.
 
==Uses==
Anonymous functions can be used to contain functionality that need not be named and possibly for short-term use. Some notable examples include [[Closure (computer science)|closure]]s and [[currying]].
 
===Sorting===
When attempting to sort in a non-standard way it may be easier to contain the comparison logic as an anonymous function instead of creating a named function.
 
In python, consider sorting items in a list by the name of their class:
 
<source lang="python">
a = [10, '10', 10.0]
a.sort(lambda x,y: cmp(x.__class__.__name__, y.__class__.__name__))
</source>
 
which results in
<source lang="python">
[10.0, 10, '10']
</source>
 
Note that 10.0 has class name "float", 10 has class name "int", and '10' has class name "str". The sorted order is "float", "int", then "str".
 
The anonymous function in this example is the lambda expression:
<source lang="python">
lambda x,y: cmp(...)
</source>
 
The anonymous function accepts two argument &mdash; x & y &mdash; and returns the comparison between them using the built-in function cmp().
Another example would be sorting a list of strings by length of the string:
 
<source lang="python">
a = ['three', 'two', 'four']
a.sort(lambda x,y: cmp(len(x), len(y)))
</source>
 
which results in
<source lang="python">
['two', 'four', 'three']
</source>
 
which clearly has by sorted by length of the strings.
 
==List of languages==