Anonymous function

From Wikipedia, the free encyclopedia

In computing, 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.

Contents

[edit] Uses

Anonymous functions can be used to contain functionality that need not be named and possibly for short-term use. Some notable examples include closures and currying.

All of the code in the following sections is in python.

[edit] 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. Most languages provide a generic sort function that implements a sort algorithm that will sort arbitrary objects. This function usually accepts an arbitrary comparison function that is supplied two items and the function indicates if they are equal or if one is "greater" or "less" than the other (typically indicated by returning a negative number, zero, or a positive number).

Consider sorting items in a list by the name of their class (everything in python has a class):

a = [10, '10', 10.0]
a.sort(lambda x,y: cmp(x.__class__.__name__, y.__class__.__name__))
print a
[10.0, 10, '10']

Note that 10.0 has class name "float", 10 has class name "int", and '10' has class name "str". The sorted order is "float", "int", then "str".

The anonymous function in this example is the lambda expression:

lambda x,y: cmp(...)

The anonymous function accepts two arguments — x & y — and returns the comparison between them using the built-in function cmp(). Another example would be sorting a list of strings by length of the string:

a = ['three', 'two', 'four']
a.sort(lambda x,y: cmp(len(x), len(y)))
print a
['two', 'four', 'three']

which clearly has been sorted by length of the strings.

[edit] Closures

Closures are functions evaluated in an environment containing bound variables. The following example binds the variable "threshold" in an anonymous function that compares the input to the threshold.

def comp(threshold):
  return lambda x: x < threshold

This can be used as a sort of generator of comparison functions:

a = comp(10)
b = comp(20)
 
print a(9), a(10), a(20), a(21)
True False False False
 
print b(9), b(10), a(20), b(21)
True True False False

It would clearly be very impractical to create a function for every possible comparison function and may be too inconvenient to keep the threshold around for further use. Regardless of the reason why a closure is used the anonymous function is what the contains the functionality that does the comparing.

[edit] Currying

Main article: currying

Currying is transforming a function from multiple inputs to fewer inputs (in this case integer division).

def divide(x,y):
  return x/y
 
def divisor(d):
  return lambda x: divide(x,d)
 
half = divisor(2)
third = divisor(3)
 
print half(32), third(32)
16 10
 
print half(40), third(40)
20 13

While the use of anonymous functions is perhaps not common with currying it still can be used. In the above example, the function divisor generates functions with a specified divisor. The functions half and third curry the divide function with a fixed divisor.

(It just so happens that the divisor function forms a closure as well as curries by binding the "d" variable.)

[edit] Map

The map function performs a function call on each element of an array. The following example squares every element in an array with an anonymous function.

a = [1, 2, 3, 4, 5, 6]
print map(lambda x: x*x, a)
[1, 4, 9, 16, 25, 36]

The anonymous function accepts an argument and multiplies it by itself (squares it).

[edit] Fold

The fold/reduce function reduces a list of elements repeatedly from left-to-right until only one element remains.

a = [1, 2, 3, 4, 5]
print reduce(lambda x,y: x*y, a)
120

This performs:


\left(
 \left(
  \left(
   1 \times 2
  \right)
  \times 3
 \right)
 \times 4
\right)
\times 5
= 120

The anonymous function here is simply the multiplication of the two arguments.

[edit] List of languages

The following is a list of programming languages that fully support unnamed anonymous functions; support some variant of anonymous functions; and have no support for anonymous functions.

This table shows some general trends. First, the languages that do no support anonymous functions — C, C++, C# †, Java — all employ static typing. This does not, however, mean that static languages are incapable of support anonymous functions. Second, the languages that treat functions as first-class functionsJavaScript, Lisp, Scheme, ML, Haskell, Python,Ruby, Perl — generally have anonymous function support.

Language Full support Some support No support
ActionScript Check markY
C Check markY
C++ Check markY
C# v1 Check markY
C# v2 Check markY
C# v3 Check markY
Curl Check markY
VB v9 Check markY
Haskell Check markY
Java Check markY
JavaScript Check markY
Lisp Check markY
Lua Check markY
all ML languages
(OCaml, Standard ML, etc.)
Check markY
Perl Check markY
Python Check markY
PHP Check markY
Ruby Check markY
Scheme Check markY

† — C# support for anonymous functions currently employs the creation of a static function within the class. This means anonymous function support is a convenient facade presented by the compiler while the created anonymous function is really just a named static function (with a semi-random name) and thus not a real anonymous function. What this ultimately means is that anonymous functions are not dynamically created and executed like in, say, JavaScript.

[edit] Examples

Numerous languages support anonymous functions, or something similar.

[edit] C#

Support for anonymous functions in C# has deepened through the various versions of the language compiler. The C# Language v3.0, released in November 2007 with the .NET Framework v3.5, has full support of anonymous functions. The term for it in C# is "lambda expressions". See the C# 3.0 Language Specification, section 5.3.3.29, for more information.

Func<int,int> foo = (x) => { return x*x; } ;
Console.WriteLine(foo(7));

While the function is anonymous, the type is explicit. C# 3.0 does include implicitly typed variables, but because the lambda syntax may be used to denote an anonymous function or an expression tree, the type cannot automatically be inferred by the compiler, and therefore lambda expressions cannot be assigned to implicitly typed variables. Eg,this does not work:

// will NOT compile!
var foo = (x) => { return x*x; } ;
Console.WriteLine(foo(7));

As a further example, combining anonymous functions with the Map capability available with System.Collections.Generic.List (in the ConvertAll() method) looks like this:

// Initialize the list:
System.Collections.Generic.List<int> Values = new System.Collections.Generic.List<int>() { 7, 13, 4, 9, 3 };
// Map the anonymous function over all elements in the list, return the new list
var foo = Values.ConvertAll((d) => { return d*d; }) ; 
// the result of the foo variable is of type System.Collections.Generic.List<Int32>

Prior versions of C# had more limited support for anonymous functions. C# v1.0, introduced in February 2002 with the .NET Framework v1.0, provided partial anonymous function support through the use of delegates. This construct is somewhat similar to PHP delegates. In C# 1.0, Delegates are like function pointers that refer to an explicitly named method within a class. (but unlike PHP the name is not required at the time the delegate is used.) C# v2.0, released in November 2005 with the .NET Framework v2.0, introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 continues to support these constructs, but also supports the lambda expression construct.

This example will compile in C# 3.0, and exhibits the three forms:

public class TestDriver
  {
    delegate int SquareDelegate(int d);
    static int Square(int d)
    {
      return d*d;
    }
 
    static void Main(string[] args)
    {
      // C# 1.0: Original delegate syntax required 
      // initialization with a named method.
      SquareDelegate A = new SquareDelegate(Square);
      System.Console.WriteLine(A(3));
 
      // C# 2.0: A delegate can be initialized with
      // inline code, called an "anonymous method." This
      // method takes a string as an input parameter.
      SquareDelegate B = delegate(int d) { return d*d; };
      System.Console.WriteLine(B(5));
 
      // C# 3.0. A delegate can be initialized with
      // a lambda expression. The lambda  takes a int, and returns an int. 
      // The type of x is inferred by the compiler.
      SquareDelegate C = (x) => { return x*x; };
      System.Console.WriteLine(C(7));
 
      // C# 3.0. A delegate that accepts a single input and
      // returns a single output can also be implicitly declared with the Func<> type.
      System.Func<int,int> D = (x) => { return x*x; };
      System.Console.WriteLine(D(9));
 
    } 
  }


In the case of the C# 2.0 version, the C# compiler takes the code block of the anonymous function and creates a static private function. Internally, the function gets a generated name, of course; this generated name is based on the name of the method in which the Delegate is declared. But the name is never exposed to application code.

In the case of the C# 3.0 version, the same mechanism applies.

[edit] 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 - in fact, all functions are implemented in the same way as anonymous functions, only sometimes with slightly different semantics (e.g. function foo(x) { return x*x } is the same as foo given above).

[edit] Lisp

Lisp supports anonymous functions.

(lambda (arg) (* arg arg))

[edit] Lua

In Lua all functions are anonymous. A "function name" in Lua is actually a variable that holds the respective function [1].

Thus, in Lua

function foo (x) return 2*x end

is just syntactical sugar for

foo = function (x) return 2*x end

An example of using anonymous functions for reverse-order sorting:

table.sort(network, function (a,b)
  return (a.name > b.name)
end)

[edit] Perl

Perl supports anonymous functions, as follows:

(sub { print "I got called\n" })->();         # 1. fully anonymous, called as created
 
my $squarer = sub { my $x = shift; $x * $x }; # 2. assigned to a variable
 
sub curry (&@) {
    my ($sub, @args) = @_;
    return sub { $sub->(@args, @_) };         # 3. as a return value of another function
}
 
# example of currying in Perl
sub sum { my $tot = 0; $tot += $_ for @_; $tot } # returns the sum of its arguments
my $curried = curry \&sum, 5, 7, 9;
print $curried->(1,2,3), "\n";    # prints 27 ( = 5 + 7 + 9 + 1 + 2 + 3 )

Other constructs take "bare blocks" as arguments, which serve a function similar to lambda functions of a single parameter, but don't have the same parameter-passing convention as functions -- @_ is not set.

my @squares = map { $_ * $_ } 1..10;   # map and grep don't use the 'sub' keyword
my @square2 = map $_ * $_, 1..10;      # parentheses not required for a single expression
 
my @bad_example = map { print for @_ } 1..10; # values not passed like normal Perl function

[edit] 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;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);

As of 5.2.5, the contents of $foo is a string of the form "\0lambda_X" where \0 is a null character (ASCII value zero) and X is a number starting with one.

It is important to note that the argument list and function body must be in single quotes or the dollar signs must be escaped. Otherwise PHP will assume "$x" means the variable $x and will substitute it into the string (despite possibly not existing) instead of leaving "$x" in the string. For functions with quotes or functions with lots of variables, it can get quite tedious to ensure the intended function body is what PHP interprets.

[edit] 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.

[edit] Visual Basic

VB v9, introduced in November 2007, supports anonymous functions through the lambda form. Combined with implicit typing, VB provides an economical syntax for anonymous functions. As with Python, in VB v9, anonymous functions must be defined on a single line; they cannot be compound statements. Further, an anonymous function in VB must truly be a VB "Function" - it must return a value.

Dim foo = Function(x) x * x
Console.WriteLine(foo(10))

[edit] References