FACTOID # 5: Minnesota and Connecticut are both in the top 5 in saving money and total tax burden per capita.
 
 Home   Encyclopedia   Statistics   States A-Z   Flags   Maps   FAQ   About 
   
 
WHAT'S NEW
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Closure (computer science)

In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Constructs such as objects in other languages can also be modeled with closures. Computer science, or computing science, is the study of the theoretical foundations of information and computation and their implementation and application in computer systems. ... In computer science, a subroutine (function, procedure, or subprogram) is a sequence of code which performs a specific task, as part of a larger program, and is grouped as one, or more, statement blocks; such code is sometimes collected into software libraries. ... In mathematics, and in other disciplines involving formal languages, including mathematical logic and computer science, a free variable is a notation for a place or places in an expression, into which some definite substitution may take place, or with respect to which some operation (summation or quantification, to give two... Functional programming is a programming paradigm that conceives computation as the evaluation of mathematical functions and avoids state and mutable data. ... ML is a general-purpose functional programming language developed by Robin Milner and others in the late 1970s at the University of Edinburgh, whose syntax is inspired by ISWIM. Historically, ML stands for metalanguage as it was conceived to develop proof tactics in the LCF theorem prover (the language of... “LISP” redirects here. ... Object-oriented programming (OOP) is a computer programming paradigm in which a software system is modeled as a set of objects that interact with each other. ...


In some languages, a closure may occur when a function is defined within another function, and the inner function refers to local variables of the outer function. At runtime, when the outer function executes, a closure is formed, consisting of the inner function’s code and references to any variables of the outer function required by the closure. In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination (compare compile time). ...


A closure can be used to associate a function with a set of "private" variables, which persist over several invocations of the function. The scope of the variable encompasses only the closed-over function, so it cannot be accessed from other program code. However, the variable is of indefinite extent, so a value established in one invocation remains available in the next. As a consequence, closures can be used to hide state, and thus to implement object-oriented programming. In computer programming, scope is an enclosing context where values and expressions are associated. ... In computer science and mathematics, a variable (IPA pronunciation: ) (sometimes called a pronumeral) is a symbolic representation denoting a quantity or expression. ... In computer science, the principle of information hiding is the hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed. ... Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. ...


The concept of closures was developed in the 60’s and was first fully implemented as a language feature in the programming language Scheme. Since then, many languages have been designed to support closures. Scheme is a multi-paradigm programming language. ...

Contents

Closures and first-class functions

Closures typically appear in languages in which functions are first-class values—in other words, such languages allow functions to be passed as arguments, returned from function calls, bound to variable names, etc., just like simpler types such as strings and integers. For example, consider the following Scheme function: In computer science, a programming language is said to support first-class functions if it treats functions as first-class objects. ...

 ; Return a list of all books with at least THRESHOLD copies sold. (define (best-selling-books threshold) (filter (lambda (book) (>= (book-sales book) threshold)) book-list)) 

In this example, the lambda expression (lambda (book) (>= (book-sales book) threshold)) appears within the function best-selling-books. When the lambda expression is evaluated, Scheme creates a closure consisting of the code for the lambda and a reference to the threshold variable, which the lambda uses.


The closure is then passed to the filter function, which calls it repeatedly to determine which books are to be added to the result list and which are to be discarded. Because the closure itself has a reference to threshold, it can use that variable each time filter calls it. The function filter itself might be defined in a completely separate file.


Here is the same example rewritten in ECMAScript, another popular language with support for closures: ECMAScript is a scripting programming language, standardized by Ecma International in the ECMA-262 specification. ...

 // Return a list of all books with at least 'threshold' copies sold. function bestSellingBooks(threshold) { return bookList.filter( function(book) { return book.sales >= threshold; } ); } 

The function keyword is used here instead of lambda, and an Array.filter method [1] instead of a global filter function, but otherwise the structure and the effect of the code is the same.


A function may create a closure and return it. The following example is a function that returns a function.


In Scheme:

 ; Return a function that approximates the derivative of f ; using an interval of dx, which should be appropriately small. (define (derivative f dx) (lambda (x) (/ (- (f (+ x dx)) (f x)) dx))) 

In ECMAScript:

 // Return a function that approximates the derivative of f // using an interval of dx, which should be appropriately small. function derivative(f, dx) { return function(x) { return (f(x + dx) - f(x)) / dx; }; } 

Because the closure in this case outlives the scope of the function that creates it, the variables f and dx live on after the function derivative returns. In languages without closures, the lifetime of a local variable coincides with the execution of the scope where that variable is declared. In languages with closures, variables must continue to exist as long as any existing closures have references to them. This is most commonly implemented using some form of garbage collection. In computer programming, scope is an enclosing context where values and expressions are associated. ... In computer science, garbage collection (GC) is a form of automatic memory management. ...


Uses of closures

Closures have many uses:

  • Designers of software libraries can allow users to customize behavior by passing closures as arguments to important functions. For example, a function that sorts values can accept a closure argument that compares the values to be sorted according to a user-defined criterion.
  • Because closures delay evaluation—i.e., they do not "do" anything until they are called—they can be used to define control structures. For example, all Smalltalk's standard control structures, including branches (if/then/else) and loops (while and for), are defined using objects whose methods accept closures. Users can easily define their own control structures as well.
  • Multiple functions can be produced which close over the same environment, enabling them to communicate privately by altering that environment.
  • Closures can be used to implement object systems [2], and may in fact be better alternatives to objects [3].

Note: Some speakers call any data structure that binds a lexical environment a closure, but the term usually refers specifically to functions. Illustration of an application which may use libvorbisfile. ... In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a list in a certain order. ... For other uses, see Small talk. ... Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. ...


Differences in semantics

As different languages do not always have a common definition of the lexical environment, their definitions of closure may vary as well. The commonly held minimalist definition of the lexical environment defines it as a set of all bindings of variables in the scope, and that is also what closures in any language have to capture. It should be noted though that the meaning of a variable binding also differs. In imperative languages, variables bind to locations in memory, which can in turn store values. The binding can never change, but the value in the bound location can. In such languages, since closure captures the binding, any operation on the variable, whether done from the closure or not, is performed on the same memory location. Here is an example illustrating the concept in ECMAScript, which is one such language: In programming languages, name binding refers to the association of values with identifiers. ... In computer science and mathematics, a variable (IPA pronunciation: ) (sometimes called a pronumeral) is a symbolic representation denoting a quantity or expression. ... ECMAScript is a scripting programming language, standardized by Ecma International in the ECMA-262 specification. ...

 var f, g; function foo() { var x = 0; f = function() { return ++x; }; g = function() { return --x; }; x = 1; print(f()); // "2" } foo(); print(g()); // "1" print(f()); // "2" 

Note how function foo, as well as both closures, use the same memory location bound to local variable x together.


On the other hand, many functional languages, such as ML, bind variables directly to values. In this case, since there is no way to change the value of the variable once it is bound, there is no need to share the state between closures - they just use the same values. ML is a general-purpose functional programming language developed by Robin Milner and others in the late 1970s at the University of Edinburgh, whose syntax is inspired by ISWIM. Historically, ML stands for metalanguage as it was conceived to develop proof tactics in the LCF theorem prover (the language of...


Yet another subset, lazy functional languages such as Haskell, bind variables to a result of a computation in the future. Consider this example in Haskell: Haskell is a standardized purely functional programming language with non-strict semantics, named after the logician Haskell Curry. ...

 foo x y = let r = x / y in (z -> z + r) f = foo 1 0 main = do putStr (show (f 123)) 

The binding of r captured by the closure defined within function foo is to the computation (x / y) - which in this case results in division by zero. However, since it is the computation that is captured, and not the value, the error only manifests itself when the closure is invoked, and actually attempts to use the captured binding.


Yet more differences manifest themselves as other lexically scoped constructs, such as return, break and continue statements in C-like languages. Such constructs can in general be considered to be accessible lexical bindings to an escape continuation (in case of break and continue, such interpretation requires looping constructs to be considered in terms of recursive function calls). In some languages, such as ECMAScript, this binding is implicitly reintroduced in every closure, thus hiding the lexical binding from the enclosing scope - thus, a return statement from within the closure transfers control to the code which called it. In Smalltalk, however, only top-level definitions introduce such binding, and closures capture it rather than rebinding it. The following examples in ECMAScript and Smalltalk highlight the difference: For other uses, see Continuation (disambiguation). ... For other uses, see Small talk. ...

 "Smalltalk" foo | xs | xs := #(1 2 3 4). xs do: [:x | ^x]. ^0 bar Transcript show: (self foo) "prints 1" 
 // ECMAScript function foo() { var xs = new Array(1, 2, 3, 4); xs.forEach(function(x) { return x; }); return 0; } print(foo()); // prints 0 

Both code snippets seem to do the same thing at the first glance, bearing in mind that ^ in Smalltalk is analogous to ECMAScript return. The difference is that in ECMAScript example, return will leave the closure, but not function foo, whereas in Smalltalk example, ^ will return from method foo, and not just from the closure. The latter allows more expressiveness - in Smalltalk, do: is defined as a plain method, and there is nothing special about it, while ECMAScript has to introduce a special language construct, foreach, to express the same thing. On the other hand, there is an issue of captured continuation outliving the scope in which it was created. Consider:

 foo ^[ x: | ^x ] bar | f | f := self foo. f value: 123 "error!" 

When block returned by method foo is invoked, it attempts to return a value from foo. Since the call to foo has already completed, this operation results in an error.


Some languages, such as Ruby, allow the programmer to choose the way he wants return to be captured. An example in Ruby: Ruby is a reflective, dynamic, object-oriented programming language. ...

 def foo f = Proc.new { return "return from foo from inside proc" } f.call # control leaves foo here return "return from foo" end def bar f = lambda { return "return from lambda" } f.call # control does not leave bar here return "return from bar" end puts foo # prints "return from foo from inside proc" puts bar # prints "return from bar" 

Both Proc.new and lambda in this example are ways to create a closure, but semantics of the closures thus created are different with respect to the return statement.


Implementation and theory

Closures are typically implemented with a special data structure that contains a pointer to the function code, plus a representation of the function's lexical environment (e.g., the set of available variables and their values) at the time when the function was created. A binary tree, a simple type of branching linked data structure. ...


A language implementation cannot easily support full closures if its run-time memory model allocates all local variables on a linear stack. In such languages, a function's local variables are deallocated when the function returns. However, a closure requires that the free variables it references survive the enclosing function's execution. Therefore those variables must be allocated so that they persist until no longer needed. This explains why typically languages that natively support closures use garbage collection. In computer science, garbage collection (GC) is a form of automatic memory management. ...


A typical modern Scheme implementation allocates local variables that might be used by closures dynamically and stores all other local variables on the stack.


Closures are closely related to Actors in the Actor model of concurrent computation where the values in the function's lexical environment are called acquaintances. An important issue for closures in concurrent programming languages is whether the variables in a closure can be updated and if so how these updates can be synchronized. Actors provide one solution (Will Clinger 1981). In computer science, the Actor model is a mathematical model of concurrent computation that treats actors as the universal primitives of concurrent digital computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to... Parallel programming (also concurrent programming), is a computer programming technique that provides for the execution of operations concurrently, either within a single computer, or across a number of systems. ... Year 1981 (MCMLXXXI) was a common year starting on Thursday (link displays the 1981 Gregorian calendar). ...


See also

The lambda calculus is a formal system designed to investigate function definition, function application, and recursion. ... Funarg is an abbreviation for functional argument; in computer science, the funarg problem relates to the difficulty of implementing functions as first-class objects in stack-based programming language implementations. ... In computing, a continuation is a representation of some of the execution state of a program (often the call stack and the current Instruction pointer) at a certain point. ... A spaghetti stack is in fact an N-ary tree data structure in which child nodes have pointers to the parent nodes. ... Value-level programming refers to one of the two contrasting programming paradigms identified by John Backus in his work on Programs as mathematical objects, the other being Function-level programming. ... In object-oriented programming, the Command pattern is a design pattern in which objects are used to represent actions. ... Eiffel is an ISO-standardized object-oriented programming language designed for extensibility, reusability, reliability and programmer productivity. ... An anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to a name. ...

References

  • Will Clinger. Foundations of Actor Semantics. MIT Mathematics Doctoral Dissertation. June 1981.

External links

  • The Original "Lambda Papers": A classic series of papers by Guy Steele and Gerald Sussman discussing, among other things, the versatility of closures in the context of Scheme (where they appear as lambda expressions).

  Results from FactBites:
 
Catalog - University of Illinois at Springfield (1438 words)
The online computer science program, which is identical to the on-campus program, allows students to actively participate in dynamic, diverse, and interactive online learning communities and to complete their degrees in their own time and at their own pace via the Internet.
A minor in computer science is designed for students who wish to develop a working knowledge of the computer that will allow them to apply effective computer techniques and computational problem-solving skills in a variety of contexts.
Computer science graduate students must complete a comprehensive closure exercise to demonstrate the ability to formulate, investigate, and analyze a problem and to report results in writing and orally.
  More results at FactBites »

 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m