Anonymous function

This is an old revision of this page, as edited by Cburnett (talk | contribs) at 02:19, 12 February 2008 (List of languages: Added Scheme). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

An anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to a name. In lambda calculus, all functions are anonymous. The Y combinator can be utilised in these circumstances to provide anonymous recursion. Certain programming languages also provide support for both named and anonymous functions. The lambda calculus without anonymous function definition forms a combinatory logic.

Some object-oriented programming languages have anonymous classes, which are a similar concept. Java is such a language.

List of languages

Language Full support Some support No support
C X
C++ X
JavaScript X
Lisp X
Python X
PHP X
Scheme X

Examples

Numerous languages support anonymous functions, or something similar.

JavaScript

JavaScript supports anonymous functions.

var foo = function(x) {return x*x;}
alert(foo(10));

Unlike python, anonymous functions in JavaScript are just like named functions and are declared just like named functions.

List

Lisp supports anonymous functions.

(lambda (arg) (* arg arg))

Python

Python supports anonymous functions through the lambda form. It is, however, expected to be only a single line of code and always returns whatever that line returns. For example:

foo = lambda x: x*x
print foo(10)

The lambda function always returns x*x and there is no way for a lambda function to not return something. This makes anonymous functions limited and are not simply nameless functions.

PHP

PHP doesn't have true anonymous functions because the only way to reference functions is by name. The closest PHP is shown in the following.

$foo = create_function("$x", "return $x*$x;");
echo $foo(10);