Anonymous function

From Simple English Wikipedia, the free encyclopedia
Jump to navigation Jump to search

In computer science and mathematics, an anonymous function is a function with no name. Usually, a function is written like: . It can be written anonymously as . Anonymous functions exist in most functional programming languages and most other programming languages where functions are values.

Examples in some programming languages[change | change source]

Each of these examples show a nameless function that multiplies two numbers.

Python[change | change source]

Uncurried (not curried):

(lambda x, y: x * y)

Curried:

(lambda x: (lambda y: x * y))
</source>

When given two [[Number|numbers]]:

<syntaxhighlight lang="python">
>>>(lambda x: (lambda y: x * y)) (3) (4)
12
</source>
===Haskell===
Curried:<syntaxhighlight lang="haskell">
\x -> \y -> x * y
</source><syntaxhighlight lang="haskell">
\x y -> x * y

When given two numbers:

>>> (\x -> \y -> x * y) 3 4
12
</source>

The function can also be written in [[point-free|point-free (tacit)]] style:
<syntaxhighlight lang="haskell">
(*)
</source>

===Standard ML===
Uncurried:
<syntaxhighlight lang="sml">
fn (x, y) => x * y
</source>

Curried:
<syntaxhighlight lang="sml">
fn x => fn y => x * y
</source>Point-free:<syntaxhighlight lang="sml">
(op *)

JavaScript[change | change source]

Uncurried:

(x, y) => x * y
function (x, y) {
  return x * y;
}

Curried:

x => y => x * y
function (x) {
  return function (y) {
    return x * y;
  };
}
</source>

===Scheme===
Uncurried:<syntaxhighlight lang="scheme">
(lambda (x y) (* x y))

Curried:

(lambda (x) (lambda (y) (* x y)))
</source>Point-free:<syntaxhighlight>
*

C++ 11[change | change source]

Uncurried: <syntaxhighlight lang="cpp"> [](int x, int y)->int { return x * y; }; </source> Curried: <syntaxhighlight lang="cpp"> [](int x) { return [=](int y)->int { return x * y; }; }; </source>

C++ Boost[change | change source]

Uncurried:<syntaxhighlight lang="cpp"> _1 * _2 </source> 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">

  1. include <boost/lambda/lambda.hpp>

using namespace boost::lambda; </source>

Related pages[change | change source]

Other websites[change | change source]