Jump to content

Function literal: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
fixing link
propose merge
Line 1: Line 1:
{{mergeto|First-class function}}
{{wikify|February 2007}}
{{wikify|February 2007}}



Revision as of 06:47, 11 March 2007


In Computer Science, a function literal is a literal for functions. In contrast to the declaration of a function, no name is associated to a function literal and function literals are also referred to as Anonymous function. Depending on the language, variables in function literals are bound to different scopes: a function only referring to local variables of this function is a pure function, a function referring to the environment is a closure. Function literals often use Lambda-Notation where the keyword lambda is followed by the arguments of the function and then the code used to evaluate the function.

The function literal is useful whenever one function needs to be passed another (higher order) function as argument. Examples are the registration of callback functions, sorting functions or functions like map or reduce.

Examples of function literals

Lisp

(lambda (a b) (* a b)) ; function literal
((lambda (a b) (* a b)) 4 5) ; function is passed 4 and 5

ECMAScript

function(message) { print(message); } // function literal
SomeObject.SomeCallBack=function(message) { print(message); } // function literal assigned to callback

Note that the callee keyword in ECMAScript makes it possible to write recursive functions without naming them.

Python

Python does not have a (full) function literal, because lambda can only be followed an expression and not statements.

lambda x:x*x # function literal 
map(lambda x:x*x,range(1:10)) # array of first ten square numbers