Anonymous function
In computer science and mathematics, an anonymous function is a function with no name. Usually, a function is written like: [math]\displaystyle{ f(x) = x^2 - x + 42 }[/math]. It can be written anonymously as [math]\displaystyle{ x \rightarrow x^2 - x + 42 }[/math]. Anonymous functions exist in most functional programming languages and most other programming languages where functions are values.
Examples in some programming languages
Each of these examples show a nameless function that multiplies two numbers.
Python
Uncurried (not curried):<syntaxhighlight lang="python3"> (lambda x, y: x * y) </syntaxhighlight>Curried:<syntaxhighlight lang="python"> (lambda x: (lambda y: x * y)) </syntaxhighlight>
When given two numbers:
<syntaxhighlight lang="python"> >>>(lambda x: (lambda y: x * y)) (3) (4) 12 </syntaxhighlight>
Haskell
Curried:<syntaxhighlight lang="haskell"> \x -> \y -> x * y </syntaxhighlight><syntaxhighlight lang="haskell"> \x y -> x * y </syntaxhighlight>When given two numbers:
<syntaxhighlight lang="haskell"> >>> (\x -> \y -> x * y) 3 4 12 </syntaxhighlight>
The function can also be written in point-free (tacit) style: <syntaxhighlight lang="haskell"> (*) </syntaxhighlight>
Standard ML
Uncurried: <syntaxhighlight lang="sml"> fn (x, y) => x * y </syntaxhighlight>
Curried: <syntaxhighlight lang="sml"> fn x => fn y => x * y </syntaxhighlight>Point-free:<syntaxhighlight lang="sml"> (op *) </syntaxhighlight>
JavaScript
Uncurried:<syntaxhighlight lang="javascript"> (x, y) => x * y </syntaxhighlight><syntaxhighlight lang="javascript"> function (x, y) {
return x * y;
} </syntaxhighlight>Curried:<syntaxhighlight lang="javascript"> x => y => x * y </syntaxhighlight><syntaxhighlight lang="javascript"> function (x) {
return function (y) { return x * y; };
} </syntaxhighlight>
Scheme
Uncurried:<syntaxhighlight lang="scheme"> (lambda (x y) (* x y)) </syntaxhighlight>Curried:<syntaxhighlight lang="scheme"> (lambda (x) (lambda (y) (* x y))) </syntaxhighlight>Point-free:<syntaxhighlight>
</syntaxhighlight>
C++ 11
Uncurried: <syntaxhighlight lang="cpp"> [](int x, int y)->int { return x * y; }; </syntaxhighlight> Curried: <syntaxhighlight lang="cpp"> [](int x) { return [=](int y)->int { return x * y; }; }; </syntaxhighlight>
C++ Boost
Uncurried:<syntaxhighlight lang="cpp"> _1 * _2 </syntaxhighlight> Note: What you need to write boost lambda is to include <boost/lambda/lambda.hpp> header file, and using namespace boost::lambda, i.e. <syntaxhighlight lang="cpp">
- include <boost/lambda/lambda.hpp>
using namespace boost::lambda; </syntaxhighlight>