What are closures in programming languages?

Source: Internet
Author: User
First of all, I think it is not necessary to understand or learn a concept if it is not understood or affected. Closure is such a concept that you can use well without understanding it. I have been writing as3 programs in the past two years. I have been dealing with as3 programs every day. I have even had one function set, and one method has more than 20 function extreme examples, but we never know how it works. it's just like water and air. we don't need it.

First of all, I think it is not necessary to understand or learn a concept if it is not understood or affected. Closure is such a concept that you can use well without understanding it. I have been writing as3 programs in the past two years. I have been dealing with as3 programs every day. I have even had one function set, and one method has more than 20 function extreme examples, but I have never studied how it is implemented. like water and air, we don't need to know that water is H2O, air is a mixture of oxygen, nitrogen, carbon dioxide, and so on.

Secondly, I think the online explanation of the closure concept is too narrow, and it seems like I ++ and I are back. If you have to understand this concept and understand it like that, the gains are too small to be worth it.

The interpretation of closures in Wikipedia is classic: In computer science, Closure is short for Lexical Closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment. Peter J. Landin defined the term closure as an entity that contains environmental and control components in 1964.

Below are the closure concepts I understand.

First look at the closure in mathematics.

() Is an interval. However, when analyzing and calculating this interval, we often use values 1 and 5 that do not belong to this interval. [] is).

In our daily lives, we need to go to department A and department A to create A chapter for Department B. department B said, you must first build A chapter for department C, department C said that this is not our function scope ...... Play the ball. this is a non-closure. Closure is responsible for the end. if you find Department A, the person who receives Department A is responsible for the end, and he/she coordinates Department B and department C.

In the project, closure is the project manager responsible for scheduling the resources required by the project. If there is anything for the boss and the customer, you can directly find the project manager without looking for other people.

In programming languages, closure is a syntactic sugar. it automatically packs all the resources involved in our purpose and our purpose in a natural form, use it in a natural way that is as easy as possible to avoid misunderstanding. As for its specific implementation, I personally agree that, without affecting the use of the service, I will not provide a thorough explanation. In many cases, you need to access external local variables in a piece of code. if this syntax sugar is not provided, you need to write a lot of code. with the syntax sugar of closure, you don't need to write so much code, so you can use it naturally.

In this way, the closure can be upgraded from a syntax mechanism to a design principle: the closure is a design concept from the user's perspective, based on the context analysis, you have done everything about zookeeper, complex things, and external environment interaction by yourself, leaving users with a natural interface.

Under this principle, in functional languages, the so-called closure is just a "closure", and there are a large number of other types of "closure" waiting for discovery and implementation.

Below are some examples of closure design principles.

Positive example: the data binding syntax in Flex is a "closure ". X = "{B. num + c. num} ", for this syntax, the compiler automatically goes to the context to find the variables called B and c, and then finds their internal num Variables. if they are all bindable, the bind chain is automatically added to them. The value of x is updated when B, c, num, and other changes exist.

Counterexample: the design in Winform violates the closure principle. when the value of some controls is not updated in this UI thread, an exception is thrown. It can only be called by invoke, but the invoke interface is very difficult to use. I believe many people are very disgusted with this.

Closures are not necessarily syntactic sugar. When we cannot directly extend the compiler, we cannot add syntactic sugar to implement the closure mechanism. at this time, we need to use the existing language mechanism to implement it. Next, we will transform the winform invoke method to meet the closure principle. The following code is used:

public class ControlFuncContext     {         public Control Control { get; private set; }         public Delegate Delegate { get; private set; }        public ControlFuncContext(Control ctl, Delegate d)         {             this.Control = ctl;             this.Delegate = d;         }        public void Invoke0()         {             if (Control.IsHandleCreated == true)             {                 try                 {                     Delegate.DynamicInvoke();                 }                 catch(ObjectDisposedException ex)                 {                 }             }         }        public void Invoke1
 
  (T obj)         {             if (Control.IsHandleCreated == true)             {                 try                 {                     Delegate.DynamicInvoke(obj);                 }                 catch (ObjectDisposedException ex)                 {                 }             }         }        public void Invoke2
  
   (T0 obj0, T1 obj1)         {             if (Control.IsHandleCreated == true)             {                 try                 {                     Delegate.DynamicInvoke(obj0, obj1);                 }                 catch (ObjectDisposedException ex)                 {                 }             }         }     }    public static class FormClassHelper     {        public static void InvokeAction(this Control ctl, Action action)         {             if (ctl.IsHandleCreated == true)             {                 ControlFuncContext fc = new ControlFuncContext(ctl, action);                 ctl.Invoke(new Action(fc.Invoke0));             }         }        public static void InvokeAction
   
    (this Control ctl, Action
    
      action, T obj)         {             if (ctl.IsHandleCreated == true)             {                 ControlFuncContext fc = new ControlFuncContext(ctl, action);                 ctl.Invoke(new Action
     
      (fc.Invoke1
      
       ), obj); } } public static void InvokeAction
       
        (this Control ctl, Action
        
          action, T0 obj0, T1 obj1) { if (ctl.IsHandleCreated == true) { ControlFuncContext fc = new ControlFuncContext(ctl, action); ctl.Invoke(new Action
         
          (fc.Invoke2
          
           ), obj0, obj1); } } }
          
         
        
       
      
     
    
   
  
 

It's easy to use. you just need to call the extension method InvokeAction directly. you don't have to consider cross-thread or non-Cross-thread "environment factors". Cross-thread calls are already done in a way that you don't have to know, encapsulate it.

For another example, writing a program often requires the function of opening an image file and processing it. It is difficult to write normally. for example, if the filter format is easy to forget, we will closure it and let users know whether it should be used, it should not be encapsulated for users to press the keyboard:

Public static void OpenFile (this Form element, Action
 
  
CallbackOnFilePath, String filter = "all files | *. * ") {String filePath; OpenFileDialog dlg = new OpenFileDialog (); dlg. filter = filter; dlg. fileOk + = (object sender, CancelEventArgs e) => {filePath = dlg. fileName; if (callbackOnFilePath! = Null) callbackOnFilePath (filePath) ;}; dlg. ShowDialog () ;}public static void OpenImageFile (this Form element, Action
  
   
CallbackOnFilePath, String filter = "image file | *. bmp; *. jpg; *. gif; *. png") {OpenFile (element, callbackOnFilePath, filter );}
  
 

Another example is in as3. In Flex, the control has a callLater method that is called at the next frame. This method is very useful. in many cases, this method is also required for non-Flex projects. Below, we simulate:

package orc.utils {     import flash.display.Stage;     import flash.events.Event;    public class CallLaterHelper     {         public function CallLaterHelper(stage:Stage, callback:Function)         {             this.callback = callback;             this.stage = stage;            stage.addEventListener(Event.ENTER_FRAME, onStageEnterFrame);         }         private var stage:Stage;         private var callback:Function;         private function onStageEnterFrame(event:Event):void         {             stage.removeEventListener(Event.ENTER_FRAME, onStageEnterFrame);             if(callback != null)             {                 callback();             }         }     } }

Then, in the basic control, the callLater method is provided:

public function callLater(callback:Function):void {     new CallLaterHelper(this.stage,callback); }

Summary:

  1. A closure is a design principle. it analyzes the context to simplify user calls, so that users can achieve their purpose without knowing it;
  2. The mainstream articles on closure analysis on the Internet are actually opposite to the closure principle. if you need to know the closure details, this closure fails to be designed;
  3. Try to learn as little as possible.

This article is available at http://www.nowamagic.net/librarys/veda/detail/1696.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.