Closure (computer programming): Difference between revisions

Content deleted Content added
Link to wikipedia page of function objects
Tag: Reverted
Line 74:
 
== Applications ==
The use of closures is associated with languages where functions are [[first-class object]]s, inisdfn 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 (programmingprs ogramming language)|ML]], as well as many modern, multi-paradigm languages, such asassf
[[Julia (programming language)|Julia]],
[[Python (programming languagelasfsdnguage)|Python]] and
[[Rust (programming language)|Rust]].
Closures are also frequently used with [[Callback (computer programming)|callback]]s, 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.
sdf
 
=== First-class functions ===
{{further|First-class function}}
Line 94:
</syntaxhighlight>
 
In this example, the [[Lambda (programming)|lambdalamsd fbda 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 itself has a reference to <code>threshold</code>, it can use that variable each time <code>filter</code> calls it. The function <code>filter</code> itself might be defined in a completely separate file.