[IOS, Unity, Android] talking about how to use closures

Source: Internet
Author: User

Preface

The speed at which our programming language is progressing is lagging behind the speed of hardware development.

In recent years, however, the closure syntax has its own form of expression in each language, such as

The use of function pointers as the entry point for callback functions in C languages;

Lambda syntax expressions in the Java and C # languages;

The blocks grammar in objective-c language;

The delegates grammar in C# language;

The functions object in C++ language;

History

In 1964, Peter J. Landin defined the term closure as an entity containing environmental components and control components for evaluating expressions on his SECD machine. Joel Moses that Landin invented the term closure to refer to some lambda expressions whose open bindings (free variables) have been closed (or bound) by their grammatical environment, resulting in a closed expression , or closure.

How to use

functions objects in the C + + language :

The C++11 standard begins to support closures, a special function object that is built automatically by a special language structure- lambda expression .

A C + + closure holds copies or references to all nonlocal variables.

If it is a reference to an object in an external environment, and the variables of the external environment are not present when the closure is executed (as already unwinding on the call stack), it can lead to undefined behavior, because C + + does not extend the lifetime of the variables of these referenced external environments.

The common code is as follows:

main.cpp//interface////Created by Lewis on 4/30/15.//Copyright (c), Lewis. All rights reserved.//#include <iostream> #include <string> #include <vector>using namespace std;//        Constructs a string vector vector<string> getnamelist () {static vector<string> names;    Names.push_back ("Liu Hui");    Names.push_back ("Li Jingbo");    Names.push_back ("Triya");    Names.push_back ("Zhao");    Names.push_back ("Tanghui");    Names.push_back ("Bai Zhigang");    Names.push_back ("Wang bin");    Names.push_back ("White yajing");    Names.push_back ("Zhang Hao"); return names;}        void foo (string myname) {vector<string> names = Getnamelist (); By traversing the string vector, the condition is determined using closure vector<string>::iterator i = find_if (Names.begin (), Names.end (), [&] (const string    & s) {//To determine if the operation value is equal to the parameter return s = = MyName;            }); Output Judging results cout << (String) (*i) << Endl;}        int main (int argc, const char * argv[]) {foo ("Liu Hui"); return 0;}

1. Declaring Closure variables

declaration syntax for closures in C + +, to use function type to declare the variable as follows

std::function<float(float) > colsure;

Where the first float represents the return value type of the closure, and the second float represents the closure's parameter data type as floating-point

2, assignment of the closed-packet variable

The assignment syntax for a closure in C + +, to use the [=] or [&] symbol, as shown below

Colsure = [=] (float  f) {      10.0f;       return F;};

where [=] represents the one-way assignment that we are going to make for the closure pass value

[&] often used as a reference value during use, as shown below

std:function<float(float&) >= [&] (float& f) {       10.0f ;       return f;      };

3. Use closure variables

Use [=] and [&] to declare and assign a closure variable after the end of use, the result is as follows

//declaring a floating-point variablefloatFloatvalue =1.0f;//declaring a calculated result floating-point variablefloatResultvalue =0.0f;//use a closure variable of type [=]Resultvalue =colsure (floatvalue);//Input Resultsstd::cout<<floatvalue<<":"<<resultValue<<Endl;//using a [&] Type of closure variableResultvalue =Col (floatvalue); Std::cout<<floatValue<<":"<<resultValue<<endl;

By printing the results,

1.0:10.010.0:10.0

[=] and [&] each represent two ways of value passing and reference passing.

the blocks variable in objective-c :

The system version supported by the blocks syntax is OS X 8 or later, IOS 4 or later version.

The common code is as follows:

  main.m//  blocksample////  Created by Lewis on 4/30/15.//  Copyright (c), Lewis. All rights reserved.//#import <foundation/foundation.h>nsarray *getnamelist () {    static Nsmutablearray * names = nil;        if (names = = nil) {        names = [[Nsmutablearray alloc] init];        [Names addobject:@ "Liu Hui"];        [Names addobject:@ "Triya"];        [Names addobject:@ "Li Jingbo"];        [Names addobject:@ "Zhao"];        [Names addobject:@ "Tanghui"];        [Names addobject:@ "Wang Bin"];        [Names addobject:@ "Zhang Hao"];    }        return names;} void foo (NSString *myname) {    //Get to Name list    Nsarray *names = Getnamelist ();            Use block to determine    nsinteger index = [names Indexofobjectpassingtest:^bool (id obj, Nsuinteger idx, BOOL *stop) by traversing the array object {        return [obj isequaltostring:myname];    }];            Output result    NSLog (@ "%@", Names[index]);} int main (int argc, const char * argv[]) {    foo (@ "Triya");    return 0;}

1. declaring block syntax variables

float(^block) (float);

We will find that the declaration syntax of the blocks syntax variable and the declaration syntax of the function pointer variable float(*pointer); very similar, except that there are differences in the arithmetic symbols;

2. Assigning block Syntax variables

block = ^ (float  f) {        10.0f;         return F;};

When assigning a value to a blocks variable, be aware that all of the block variables start with the "^" operation Symbol and have a block variable of the return value type. Return returns are of the same type within the block code blocks.

Detailed block syntax reference: http://www.cnblogs.com/daxiaxiaohao/p/3913467.html

lambda Expressions in the C # language:

The lambda expression is the syntactic sugar that appears in the C#4, which is used to improve the development efficiency of the program and simplify the wording of the Func type variable and the delegate object.

The common code is as follows:

Using system;using system.collections.generic;namespace lambdasample{class mainclass{public static List<string > getnamelist () {list<string> names = new list<string> (); names. Add ("Liu Hui"); names. ADD ("Triya"); names. ADD ("Li Jingbo"); names. ADD ("Zhao"); names. ADD ("Tanghui"); names. ADD ("Bai Zhigang"); return names;} public static void Foo (string myname) {//Get list of names list<string> names = Getnamelist ();//query by lambda expression as criteria string result = names. Find ((x) = = {return x = = MyName;}); /input Query result Console.WriteLine (result);} public static void Main (string[] args) {//Test foo ("Triya");}}}

1. Declaring a lambda expression variable in the C # language

In the C # language, you can declare a lambda variable through the Func type, as follows:

func<float,float> func;

Or use the delegate type to declare the lambda variable as follows:

// defines a delegate type interface Delegate float Interface (float  x);  Public Static void Main (string[] args) {     // using the interface type to declare a lambda variable      Inteface inter_func;    }

2. Lambda expression variables in the assigned C # language

In the C # language, use the = = goes to operator to generate the variable as follows:

Func = (x) + =    {10.0f;     return x;};

the left side of the goes to operator is a floating-point parameter of the closure type, and the right is the logical operation that the closure variable is prepared to include with {} .

3. Using lambda expression variables in the C # language

As with the calling function, as follows:

//declaring a func type variablefunc<float,float>func;//assigning lambda closures to FuncFunc = (x) = ={x+=10.0f; returnx;};floatFloatvalue =1.0f;floatResultvalue =0.0f;//Call the func variable, evaluate the result and assign a value to ResultvalueResultvalue =func (floatvalue);//for OutputConsole.WriteLine (Resultvalue);

Summary

In computer science, the closure (Closure) is the abbreviation of the lexical closure (Lexical Closure), which is a function that refers to the free variable. This quoted free variable will exist with this function, even if it has left the environment in which it was created. So, there is another argument that closures are entities that are composed of functions and their associated reference environment. Closures can have multiple instances at run time, and different reference environments and the same combination of functions can produce different instances.

One thing to be aware of is that

The term closure is often confused with anonymous functions . This may be because the two are often used simultaneously, but they are different concepts!!!!

[IOS, Unity, Android] talking about how to use closures

Related Article

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.