Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
Niidae Wiki
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Closure (computer programming)
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Applications == The use of closures is associated with languages where functions are [[first-class object]]s, in which functions can be returned as results from [[higher-order function]]s, or passed as arguments to other function calls; if functions with free variables are first-class, then returning one creates a closure. This includes [[functional programming]] languages such as [[Lisp (programming language)|Lisp]] and [[ML (programming language)|ML]], and many modern, multi-paradigm languages, such as [[Julia (programming language)|Julia]], [[Python (programming language)|Python]], and [[Rust (programming language)|Rust]]. Closures are also often used with [[Callback (computer programming)|callbacks]], particularly for [[event handler]]s, such as in [[JavaScript]], where they are used for interactions with a [[dynamic web page]]. Closures can also be used in a [[continuation-passing style]] to [[Information hiding|hide state]]. Constructs such as [[Object (computer science)|object]]s and [[control structure]]s can thus be implemented with closures. 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 [[Run time (program lifecycle phase)|run-time]], when the outer function executes, a closure is formed, consisting of the inner function's code and references (the upvalues) to any variables of the outer function required by the closure. === First-class functions === {{further|First-class function}} Closures typically appear in languages with [[first-class object|first-class functions]]—in other words, such languages enable 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 (programming language)|Scheme]] function: <syntaxhighlight lang="scheme"> ; 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)) </syntaxhighlight> In this example, the [[Lambda (programming)|lambda expression]] <code>(lambda (book) (>= (book-sales book) threshold))</code> appears within the function <code>best-selling-books</code>. When the lambda expression is evaluated, Scheme creates a closure consisting of the code for the lambda expression and a reference to the <code>threshold</code> variable, which is a [[free variable]] inside the lambda expression. The closure is then passed to the <code>filter</code> 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 has a reference to <code>threshold</code>, it can use that variable each time <code>filter</code> calls it. The function <code>filter</code> might be defined in a separate file. Here is the same example rewritten in [[JavaScript]], another popular language with support for closures: <syntaxhighlight lang="javascript"> // Return a list of all books with at least 'threshold' copies sold. function bestSellingBooks(threshold) { return bookList.filter(book => book.sales >= threshold); } </syntaxhighlight> The arrow operator <code>=></code> is used to define an [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions arrow function expression], and an <code>Array.filter</code> method<ref>{{cite web |url=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter |title=array.filter |work=Mozilla Developer Center |date=10 January 2010 |access-date=2010-02-09}}</ref> instead of a global <code>filter</code> function, but otherwise the structure and the effect of the code are the same. A function may create a closure and return it, as in this example: <syntaxhighlight lang="javascript"> // Return a function that approximates the derivative of f // using an interval of dx, which should be appropriately small. function derivative(f, dx) { return x => (f(x + dx) - f(x)) / dx; } </syntaxhighlight> Because the closure in this case outlives the execution of the function that creates it, the variables <code>f</code> and <code>dx</code> live on after the function <code>derivative</code> returns, even though execution has left their scope and they are no longer visible. In languages without closures, the lifetime of an automatic local variable coincides with the execution of the stack frame 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 (computer science)|garbage collection]]. === State representation === A closure can be used to associate a function with a set of "[[Class (computer programming)|private]]" variables, which persist over several invocations of the function. The [[scope (programming)|scope]] of the variable encompasses only the closed-over function, so it cannot be accessed from other program code. These are analogous to [[private variable]]s in [[object-oriented programming]], and in fact closures are similar to stateful [[function objects]] (or functors) with a single call-operator method. In stateful languages, closures can thus be used to implement paradigms for state representation and [[information hiding]], since the closure's upvalues (its closed-over variables) are of indefinite [[variable (programming)#Scope and extent|extent]], so a value established in one invocation remains available in the next. Closures used in this way no longer have [[referential transparency]], and are thus no longer [[pure function]]s; nevertheless, they are commonly used in impure functional languages such as [[Scheme (programming language)|Scheme]]. === Other uses === Closures have many uses: * 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 of [[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 also. * In languages which implement assignment, multiple functions can be produced that close over the same environment, enabling them to communicate privately by altering that environment. In Scheme: <syntaxhighlight lang="scheme"> (define foo #f) (define bar #f) (let ((secret-message "none")) (set! foo (lambda (msg) (set! secret-message msg))) (set! bar (lambda () secret-message))) (display (bar)) ; prints "none" (newline) (foo "meet me by the docks at midnight") (display (bar)) ; prints "meet me by the docks at midnight" </syntaxhighlight> * Closures can be used to implement [[Object-oriented programming|object]] systems.<ref>{{cite web |url=http://okmij.org/ftp/Scheme/oop-in-fp.txt |title=Re: FP, OO and relations. Does anyone trump the others? |date=29 December 1999 |access-date=2008-12-23 |archive-url=https://web.archive.org/web/20081226055307/http://okmij.org/ftp/Scheme/oop-in-fp.txt |archive-date=26 December 2008 |url-status=dead}}</ref> Note: Some speakers call any data structure that binds a [[Scope (programming)#Lexical scoping|lexical]] environment a closure, but the term usually refers specifically to functions.
Summary:
Please note that all contributions to Niidae Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Encyclopedia:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
Closure (computer programming)
(section)
Add topic