Content deleted Content added
→Currying: Also does a closure |
→Uses: Added higher order functions |
||
Line 5:
==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]].
All of the code in the following sections is in [[python (programming language)|python]].
===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.
<source lang="python">
Line 93 ⟶ 95:
(It just so happens that the divisor function forms a closure as well as curries by binding the "d" variable.)
===Map===
{{main|Map (higher-order function)}}
The map function performs a function call on each element of an array. The following example [[Square (algebra)|square]]s every element in an array with an anonymous function.
<source lang="python">
a = [1, 2, 3, 4, 5, 6]
print map(lambda x: x*x, a)
[1, 4, 9, 16, 25, 36]
</source>
The anonymous function accepts an argument and multiplies itself by itself (squares it).
===Fold===
{{main|Fold (higher-order function)}}
The fold/reduce function reduces a list of elements repeatedly from left-to-right until only one element remains.
<source lang="python">
a = [1, 2, 3, 4, 5]
print reduce(lambda x,y: x*y, a)
120
</source>
This performs:
:<math>
\left(
\left(
\left(
1 \times 2
\right)
\times 3
\right)
\times 4
\right)
\times 5
= 120
</math>
The anonymous function here is simply the multiplication of the two arguments.
==List of languages==
|