C + + fog landscape 8:LAMBDA expression

Source: Internet
Author: User
Tags compact

The previous C + + blog was long long ago, and the previous article looked at the contents of the lambda expression . The first time I contacted Lambda expression should be to learn the Python language when it was not quite understand the essence of this expression, followed by the link between Scala and Java8 linked calls and lambda combination of the way, deeply unable to extricate themselves. So borrow the contents of a closed package. Let's comb through the lambda expressions in C + +.

1. What is a lambda expression?

lambda Expressions are an important grammatical structure for functional programming.
LAMBDA Expression (lambda expression) is simple to say, an anonymous function, that is, a function without a function name. A lambda expression can represent a closure. (The difference between the traditional meaning of attention and mathematics). ( essentially a lambda expression is a function that operates as an anonymous object )

In fact, a programming language that lacks lambda expressions does not affect the logical expression of a programming language, and the core of the lambda expression is to provide a useful syntactic sugar: You can define a function directly without separating the definition function from the syntax, which helps to express the logic in a more compact way. If you need to define a function, it happens that the function is used only once, and then you need to define a name for it, as lazy programmers need to move out of the lambda expression. Let's look at a Python code and filter The even numbers in a list, which is a very simple requirement, let's look at the way we don't use lambda expressions:

def isOdd(n):    return n & 1;nums = [1,2,3,4,5,6]nums = filter(isOdd,nums)

Obviously it's a hassle to define an extra code logic here: first you need to jump out of running code to see the code for the defined isodd function, and secondly, the filtering logic that needs to be implemented here is simple. This is the best scenario for using lambda expressions, so let's look at how lambda expressions optimize the above code:

nums = [1,2,3,4,5,6]nums = filter(lambda x:x & 1,nums)

Well, it's elegant. The same needs are addressed with lambda expressions, and the presentation is clear:
The following usage scenarios are applicable to lambda expressions:

    • (1) The logic of code definition is more compact with the execution logic docking.
    • (2) The code is more concise.
    • (3) Ability to support closures.
Lambda expression in 2.c++

C + + Adds the syntactic structure of the lambda expression to the c++11, and the lambda syntax structure is as follows:

[capture](parameters)->return-type {body}

Next, let's analyze the meanings that each part represents, and how to use it in detail:

    • [Capture]
      capture represents an external variable, the way in which the author has an example of the contents of a closed package, and variable capture is the most complex of lambda expressions, let's take a look at the meanings of the various representations:
    • [] does not capture any variables ( but must be written, the compiler recognizes the lambda expression by capturing the structure )
    • [&} captures all variables in the outer scope by reference
    • [=] Captures all variables in the outer scope by copying
      ( both of these methods are too rough, the actual words, try to use the following pattern to qualify the referenced variable, do not arbitrarily reference )
    • [x, &y] x is passed by value, Y is passed by reference
    • [This] intercepts the this pointer in the current class. This option is added by default if you have already used & or =.

As you can see, the syntax structure of[capture] captures external variables and implements closures in such a way.

    • (parameters)
      This section is simple, similar to the list of arguments that are normally used by functions, and does not differ in how they are used.

    • ->return-type
      Explicitly indicates the type of return value returned by the lambda expression. This is generally not recommended because the C + + compiler infers the return value type of a function by type inference, and can be omitted from the preceding.

    • {Body}
      Curly braces in the body of the function, then there is nothing to say, is to implement the function of the logic of the part.

Similarly, let's take a look at how the above-mentioned Python implementation of the filter even code is implemented in C + +:

    vector<int> nums = {1,2,3,4,5,6,7};    vector<int> newNums(nums.size());        auto last = copy_if(nums.cbegin(), nums.cend(),newNums.begin(),[](int x){return !(x & 1);});    for_each(newNums.begin(), last, [](int x) {        cout << x << endl;    });

Compared to the implementation of Python, because of the lack of chained calls, it seems that the C + + implementation version does not simplify much of the application logic, but looks slightly cluttered. But this does not prevent us from using lambda expressions where appropriate to optimize our code structure.

3. Other languages and lambda expressions
    • Java
      Java in Java 8 version finally awaited the lambda expression is really to let the individual very much, personally also think Java 8 for Java this language has extremely profound influence. Let's look at how Java is implementing the above logic:

      public static void main(String[] args) {    int[] nums = {1,2,3,4,5,6,7};    IntStream.of(nums).filter((x)->{return (x & 1) == 1;}).forEach(System.out::println);}

      It's a lot more elegant than C + +, and parameter types can be type-inferred, which is really friendlier for programmers.

Frankly speaking:Java is a very lucky language, but also on the mobile development, big data wave. However, with the Google and Oracle lawsuit, do not know whether Java will continue to be a strong position in the future.

    • Golang
      There is no lambda expression, we want to be concise and clear, do not learn geek that set of things.
4. Summary

Feel this article a little bit less, spit a little more, sorry ha ~ ~ ~. About the lambda expression in C + + and we are talking about here, I hope you can use it in the actual coding, to try to concise their own code structure.

C + + fog landscape 8:LAMBDA expression

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.