What is a closure
If you ask Google to look up the word “closure,” you’ll find countless articles about closures online
The Wikipedia definition of Closure is classic: in computer science, Closure is short for Lexical Closure, a function that references free variables **. ** The referenced free variable will exist with the function, even if it has left the environment in which it was created **. Therefore, there is another way to say that closures are entities composed of functions and their associated reference environments. Peter J. Landin in 1964 defined the term closure as ** an entity that contains both an environment component and a control component. [Baidu Baike: ](http://baike.baidu.com/link?url=WWhvx0W_VK2XI-OP3OFD2Iz09amJg-mrTUCXiXmrnDYp12txFOB3Kydth0-GOZ9pdn4G6pM00CAL3AKKz5mSdq Closures are blocks of code that can contain free (unbound to a specific object) variables; These variables are not defined within the code block or in any global context, but in the context in which the code block is defined (local variables). The term “closure” comes from a combination of the code block to execute (free variables and the objects they reference are not released because they are contained in the code block) and the computational environment that provides bindings for free variables (scope).
Closure concept:
A closure is a function that has access to a variable in the scope of another function
Analyze this sentence:
1. Closures are functions defined within functions.
2. Closures can access variables that contain functions.
3. Variables referenced by closures are not released even when the include function is finished executing.
Scala, Scheme, Common Lisp, Smalltalk, Groovy, JavaScript, Ruby, Python, Go, Lua, Objective C, Swift And Java (Java8 and above), with varying degrees of support for closures.
Closures in abstract algebra
In discrete mathematics (more specifically, abstract algebra), a set is said to form a closure under an operation performed on each element of the set that results in an element of the set. For example, the set of integers constitutes a closure under subtraction; But the natural numbers do not form closures under subtraction.
Closed definition
Now that we have the concepts of sets and operations, we can define closed concepts.
Informally, operation + is closed to set A if the result of the operation + defined on set A still belongs to A. Here is a semi-formal definition of “closed” :
If for any A1, A2 ∈A, there is a1+ A2 ∈A, then the binary operation + is said to be closed for the set A. (⊙,+ with “, “or”)
For example, “+” is closed for N+, because the sum of any two positive integers is still a positive integer; But “>” is not closed to N+, e.g. 3 and 5 belong to N+, but: 3>5=>2∉N+.
Nature of the closure
A set satisfies the closure property if and only if the set is closed under some operation or collection of some operations, where “collection under some operation” means that the set is closed under each operation alone.
It is worth mentioning that this definition is often introduced into an algebraic structure as an axiom called the “closure axiom”. However, in modern set theory, operations are often formally defined as operations between sets, so it is unnecessary to introduce them into algebraic structures as axioms (because closure axioms can be indirectly defined through other axioms). However, closure axioms are still meaningful for the problem of whether subsets are closed or not.
And so on. Well, tell me. I le to… It’s so lofty, I don’t understand it at all!! ………………… All right. !!!!! Stop here… about
Closures in functional programming
In this section before you begin, I need to talk to you a clear comparison with the fact that it is in the field of functional programming when speaking of “closure”, also be the concept of index study in the field of closure, this is because the functional programming in basic theory and abstract algebra have certain affinity, so when the functional language book discussing “closure” Probably in the context of abstract mathematics. However, there can be subtle changes in presentation. In the field of functional language for mathematical closure common expression is “if a computing results can still be the operation effect, the operation is a closed”, pay attention to this is only a concept of “closure” mentioned above another equivalent expression, if we see all the results of the operation as a collection, So we can say equivalently that this operation is closed on this set.
Closures, as I describe them next, are a different concept. So when you see “closures” in the writings of functional languages, you need to be careful to distinguish which concepts they represent based on the context.
Lambda calculus and free variables
The foundation of functional programming languages is the Lambda calculus, a formal system for studying function definitions, applications, and recursion, introduced by mathematician Church in the 1930s. If you’re not familiar with lambda calculus, the Wikipedia page is a good quick start, and forgive me for not fully describing lambda calculus (there are plenty of references already).
Lambda calculus simply puts the calculation process through a series of function substitutions. For example, here is the lambda function of the addition operation (assuming the + operation is defined) : λx.λx+y
Lambda calculus is the result of repeatedly applying a function to real values and substituting real values for arguments. For example, calculate 7+2 :(λx.λx+y)7 2=>(λy.7+y)2=>7+2=>9
The first parameter (7) is used to replace the parameter (x) of the outermost function, then the second parameter (2) is used to replace the parameter (y) of the second layer function, and finally the calculation result is obtained.
Since you might crash (and I would crash) if you used the lambda calculus a lot, I’ll switch to the functional language Scheme (a dialect of Lisp) for the problem description. Note that Scheme is essentially equivalent to lambda calculus, although it only looks a little bit easier, for example not following the rules of a variant of lambda calculus: each function is only allowed to have one argument (although any multi-argument functional program can be called a lambda equivalent by a Currying process).
Here is an equivalent representation of the above lambda calculus using the scheme program :(define (f x y) (+ x y))
7+2 :(f 7 2); Value: 9
Here’s a slightly more complicated example :(define (f x) (lambda (y) (+ x y))
Here we define the function f that takes an argument x, paying special attention to its return value: not a value but an anonymous function. If we take this function out separately :(lambda (y) (+ x y))
As you can see, this anonymous function takes an argument y, but has no argument x! That is, if the function is executed out of context, x is in an unspecified state. We say that for this function, y is bound and x is free.
In general: x is a variable in the body of a function. If x is specified by the argument to the function, x is bound to the function; otherwise, x is free to the function.
As you can see below, the notion of binding and freedom of variables is a key to understanding the nature of closures. For more on this topic, read: A Ramble on Closures (From abstract Algebra and Functional Programming perspectives).
The closure nature of a programming language
Continuing with the scheme program above, we have defined the function f :(define (f x) (lambda (y) (+ x y))
If we run the following program :(f 7); Value 13: #[compound-procedure 13]
As you can see, f returns a procedure (anonymous function) which, according to the rules of function calculus, should be :(lambda (y) (+ 7 y))
Then the following operation is straightforward :(f 7) 2); Value: 9
One important thing to note here (and key to closure properties) is that this operation performs two functions: f and the anonymous function. The scope of f is (f 7), which means that after (f 7), the function f ends, and x (where 7 is assigned) is a private variable of F (bound to f), so the designer of the programming language has two choices:
First, destroy the bound variable of the function immediately after it has gone out of scope. If so, ((f 7) 2) will not yield the result, because the variable containing the value “7” will be released after the outer f operation, so the anonymous function cannot get the value of its free variable x.
Second, if a function returns another function and the returned function needs the variables of the outer function, the variables are not released immediately. Instead, the returned function is allowed to reference those variables. Languages that support this mechanism are called closures, and the inner function, along with its free variables, forms a closure.
Clearly the Scheme designers have made the second choice.
The above paragraph is not easy to understand, but be sure to read it a few times, because that’s what closures are all about.
In programming languages, closures are syntactic sugar that automatically packages our purpose and the resources involved in our purpose together in a very natural form and makes them available to use in a natural and least misleading way. As for its concrete realization, my personal opinion, in the case of not affecting the use, without understanding. In many cases, you need to access external local variables in a piece of code, and without this syntax sugar, you need to write a lot of code. With closures, you don’t have to write as much code, so you just use them naturally.
Java closures are recommended for in-depth Understanding of Java Closure Concepts.
Simple to understand: Closures can store a method as a variable that has the ability to access the free variables of its class.
Closure implementation in Java, key points:
-
How do I use variables to store methods?
-
Variables that hold methods in Java refer to ordinary objects
-
How do I give this ordinary object access to the free variables of its class?
-
The all-natural solution: inner class. The inner class has access to all properties and methods of the outer class.
-
Hiding implementations is one of the functions of inner classes. How do you ensure that you can hide implementations while passing closures to external use?
Let the inner class implement the generic interface, and then cast the inner class object up to the interface type.
The above solution is the most common implementation of closures in Java (inner class + interface)
Public final static String name = "Milk "; // name private static int num = 16; Public Milk() {system.out.println (name+" : 16/ 1 "); Public Active HaveMeals() {return new Active() {public void drink() {if(num == 0) {system.out.println (" no, you drank it all."); return; } num--; System.out.println(" drink a bottle of milk "); }}; } public void currentNum() {system.out.println (name+" remainder: "+num); } /** * interface Active {void drink(); }Copy the code
PHP closures
In PHP, closures are also called anonymous functions, which are functions with no defined name.
Function printStr() {$func $func = function($STR) {$STR = function($STR); }; $func( 'some string' ); } printStr(); Function getPrintStrFunc() {$func = function($STR) {$STR; }; return $func; } $printStrFunc = getPrintStrFunc(); $printStrFunc( 'some string' ); Function callFunc($func) {$func('some string'); } $printStrFunc = function( $str ) { echo $str; }; callFunc( $printStrFunc ); // You can also pass anonymous functions directly. CallFunc (function($STR) {echo $STR; });Copy the code
Javascript closures
function f(x){
return function(y) {
return x + y;
};
}
var lam = f(7);
console.log(lam(2));
Copy the code
In Java, closures are really not used much. In JS, closures are a must. Functional Programming from Abstract Algebra (2) : JavaScript Closures
Reference article:
Closure rambling (from the point of abstract algebra and functional programming) www.codinglabs.org/html/closur…
Brendan Eich readme brendaneich.com/2008/04/pop…
Deep understanding of Java closure concept www.zhoulujun.cn/html/java/j…
Reprint the home station article “from lambda calculus to functional programming (1) : talk about closure closure concept in Java/PHP/JS form”, please indicate the source: www.zhoulujun.cn/html/webfro…