Anonymous function

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In computer science and mathematics, an anonymous function is a function that has no name. Usually, a function is written like: f(x) = x^2 - x + 42. It can be written anonymously as x \rightarrow x^2 - x + 42 These are used in functional programming languages and other programming languages with support for anonymous functions (those which support 1st class functions).

Examples in some programming languages[change | change source]

Python[change | change source]

(lambda x: (lambda y: x * y))

The above code can be executed as a function:

>>>(lambda x: (lambda y: x * y))(3)(4)
12

Haskell[change | change source]

\x -> \y -> x * y

The above code can be executed as a function:

(\x -> \y -> x * y) 3 4

The function can also be written in point-free (tacit) style:

(*)

Standard ML[change | change source]

Not curried:

fn (x, y) => x * y
 
(* or *)
 
(op * )

Curried:

fn x => fn y => x * y

JavaScript[change | change source]

// uncurried
function(x, y)
{
    return x * y;
}
 
// curried
function(x)
{
    return (function(y)
    {
        return x * y;
    });
}

Scheme[change | change source]

;; uncurried
(lambda (x y) (* x y))
*
;; usage:
((lambda (x y) (* x y)) 3 4)
(* 3 4)
 
;; curried:
(lambda (x) (lambda (y) (* x y)))
 
;; usage:
(((lambda (x) (lambda (y) (* x y))) 3) 4)

C++ 11[change | change source]

Not curried:

[](int x, int y)->int
{
	return x * y;
};

Curried:

[](int x)
{
	return [=](int y)->int
	{
		return x * y;
	};
};

C++ Boost[change | change source]

_1 * _2

Note: What you need to write boost lambda is to include <boost/lambda/lambda.hpp> header file, and using namespace boost::lambda, i.e.

#include <boost/lambda/lambda.hpp>
using namespace boost::lambda;

You can call it as: (_1 * _2)(3, 4) to get 12.

Related pages[change | change source]

Other websites[change | change source]