First-class function

First-class function

In computer science, a programming language is said to support first-class functions (or function literal) if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions. This concept doesn't cover any means external to the language and program (metaprogramming), such as invoking a compiler or an eval function to create a new function.

These features are a necessity for the functional programming style, in which (for instance) the use of higher-order functions is a standard practice. A simple example of a higher-ordered function is the "map" or "mapcar" function, which takes as its arguments a function and a list, and returns the list formed by applying the function to each member of the list. For a language to support "map", it must support passing a function as an argument.

There are certain implementation difficulties in passing functions as arguments and returning them as results. Historically, these were termed the funarg problems, the name coming from "function argument". A different set of difficulties arises when programs can create functions at runtime; if the program is compiled, this means that the runtime environment must itself include a compiler.

Availability

Languages which are strongly associated with functional programming, such as Lisp, Scheme, ML, and Haskell, all support first-class functions. Other languages which also support them include Perl, Python, PHP, Lua, Tcl/Tk, ECMAScript (JavaScript, ActionScript), Ruby, Io, Scala, and Nemerle.

Most modern, natively compiled programming languages (e.g. C and Pascal) support function pointers, which can be stored in data structures and passed as arguments to other functions. Nevertheless, they are not considered to support first-class functions since, in general, functions cannot be created dynamically during the execution of a program. The closest analog would be a dynamically compiled function created by a just-in-time compiler, which is compiled as an array of machine language instructions in memory and then cast to a function pointer. However, this technique is specific to the underlying hardware architecture and is, therefore, neither general nor portable. The C++ programming language supports user-defined operators, including the '()' operator, which allows first-class objects to be treated as functions. Those objects can be manipulated just like any other first-class object in C++, but such manipulations do not include changing the function itself at runtime. Additionally, real Lambdas (see Lambda Calculus) have no language support in the last C++ standard (although there may be in C++0x).

Examples


= Lisp =

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

ALGOL 68

PROC newton = (REAL x, error, PROC (REAL) REAL f, f prime) REAL: # Newton's method # IF f(x) <= error THEN x ELSE newton (x - f(x) / f prime (x), error, f, f prime) FI; print(( newton(0.5, 0.001, (REAL x) REAL: x**3 - 2*x**2 + 6, (REAL x) REAL: 3*x**2 - 4**x), newline ));

ECMAScript

function(message) { print(message); } // function literalSomeObject.SomeCallBack=function(message) { print(message); } // function literal assigned to callbackNote 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 the lambda keyword can only be followed by an expression and not statements.lambda x:x*x # function literal map(lambda x:x*x,range(1,11)) # array of first ten square numbers; # same as [x*x for x in range(1,11)]

However, functions can be created dynamically; they live in the same namespace as ordinary variables, and thus it is possible to assign a function to a variable:>>> code="""def f(a):... if isinstance(a, int):... print a**2... else:... print a, 'is not an integer number'... """>>> exec(code)>>> f(3)9>>> g=f>>> g(3)9>>> g(3.0)3.0 is not an integer number>>>It is also possible to create a simple function which returns any function.

There is also possible to make code with same funcionality like in it is Javascript section below:import math

def make_derivative(f, deltaX): assert deltaX != 0.0, 'deltaX could not be zero' return lambda x: (f(x+deltaX) - f(x)) / deltaX

cos=make_derivative(math.sin, 0.0000000001)

# cos(0) ~> 1.0
# cos(math.pi/2) ~> 0.0

Javascript

Javascript supports both first class functions and lexical scope.// f: function that takes a number and returns a number// deltaX: small positive number// returns a function that is an approximate derivative of ffunction makeDerivative( f, deltaX ){ var deriv = function(x) { return ( f(x + deltaX) - f(x) )/ deltaX; } return deriv;}var cos = makeDerivative( Math.sin, 0.000001);// cos(0) ~> 1// cos(pi/2) ~> 0

ee also

*Anonymous function
*Closure
*Function object
*First-class object


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

  • First-class object — In computing, a first class object (also value, entity, and citizen), in the context of a particular programming language, is an entity which can be used in programs without restriction (when compared to other kinds of objects in the same… …   Wikipedia

  • First class — The term First class (or 1st class, Firstclass) generally implies a high level of service, importance or quality. Specific uses of the term include:* First class travel ** First class (aviation) * First Class mail * First class cricket * First… …   Wikipedia

  • First class constraint — In Hamiltonian mechanics, consider a symplectic manifold M with a smooth Hamiltonian over it (for field theories, M would be infinite dimensional). Poisson bracketsSuppose we have some constraints : f i(x)=0, for n smooth functions :{ f i } {i=… …   Wikipedia

  • Function object — A function object, also called a functor or functional, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax.Function objects are unrelated to functors in… …   Wikipedia

  • First Sergeant — is the name of a military rank used in some countries.ingaporeFirst Sergeant is a Specialist rank in the Singapore Armed Forces. First Sergeants are the most senior of the junior Specialists, ranking above Second Sergeants, and below Staff… …   Wikipedia

  • Class number formula — In number theory, the class number formula relates many important invariants of a number field to a special value of its Dedekind zeta function Contents 1 General statement of the class number formula 2 Galois extensions of the rationals 3 A …   Wikipedia

  • Function pointer — A function pointer is a type of pointer in C, C++, D, and other C like programming languages, and Fortran 2003.[1] When dereferenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function. In… …   Wikipedia

  • First-order logic — is a formal logical system used in mathematics, philosophy, linguistics, and computer science. It goes by many names, including: first order predicate calculus, the lower predicate calculus, quantification theory, and predicate logic (a less… …   Wikipedia

  • Anonymous function — 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… …   Wikipedia

  • Function word — Function words (or grammatical words) are words that have little lexical meaning or have ambiguous meaning, but instead serve to express grammatical relationships with other words within a sentence, or specify the attitude or mood of the speaker …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”