Lambda expression (Lambda Expressions)-The meaning of the notation

Source: Internet
Author: User

 Lambdaclass compiler

Let's first look at a simple lambda expression:

X=>x/2

This expression means: X is the parameter, the result of the corresponding operation on X as the return value.

With this lambda expression, we can see:

This expression does not have any type information, but it does not mean that the lambda expression is type-independent. In practice, the compiler will determine the type of x above and the type of the return value based on the context of the expression. For example:

Using System;
Using System.Linq;
public class Lambdatest
{
static void Main () {
Func<int, double> expr = x = X/2;
int somenumber = 9;
Console.WriteLine ("Result: {0}", expr (somenumber));
}
}

In the above code, the bold part is the lambda expression. Func<> for Delegate system.func<t,tresult>

The result of the above operation is: Result:4

According to the mathematical knowledge we learn, 9/2 should result in 4.5, why would the above results be 4 instead of 4.5? Because x is an integral type, the result of X/2 is also integral type, although in the above-mentioned lambda expression, we indicate that the result is double, but x/2 this expression, because X is an integral type, so the computed result has been truncated decimal, and then converted to double, so the result is 4, not 4.5

To make the result 4.5, simply define the relevant statement above as func<double,double> expr = x = X/2.

Lambda expression with no arguments:

Using System;
Using System.Linq;
public class Lambdatest
{

static void Main () {
int counter = 0;
Writestream (() = counter++);
Console.WriteLine ("Final Value of counter: {0}", counter);

}
static void Writestream (Func<int> counter) {
for (int i = 0; i < ++i) {
Console.Write ("{0},", counter ());
}
Console.WriteLine ();
}
}

(go) lambda expression (Lambda Expressions) = The meaning of the notation

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.