Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do lambdas require => as part of their syntax?

Tags:

c#

lambda

I came across this line of code in a book:

var data = db.Query(sql).OrderByDescending(c => c.DatePosted); 

This sort of thing seems like tail-chasing to me ...

Why is the c => c. necessary? Wouldn't the following be understandable (by the compiler, and even more so by humans)?

var data = db.Query(sql).OrderByDescending(DatePosted); 

I'm sure there's all kinds of fancy stuff going on behind the scenes that purportedly needs this weird lambda syntax, but again:

Why? Is it really necessary? Can't the compiler figure out DatePosted is the column by which to sort?

like image 258
B. Clay Shannon-B. Crow Raven Avatar asked Mar 07 '13 03:03

B. Clay Shannon-B. Crow Raven


People also ask

Why is lambda expression needed?

They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .

Why do we need lambda expressions in C++?

One of the new features introduced in Modern C++ starting from C++11 is Lambda Expression. It is a convenient way to define an anonymous function object or functor. It is convenient because we can define it locally where we want to call it or pass it to a function as an argument.

What are the two conditions required for using a lambda function?

In order to match a lambda to a single method interface, also called a "functional interface", several conditions need to be met: The functional interface has to have exactly one unimplemented method, and that method (naturally) has to be abstract.

What does -> mean in Java?

Basically, the -> separates the parameters (left-side) from the implementation (right side). The general syntax for using lambda expressions is. (Parameters) -> { Body } where the -> separates parameters and lambda expression body.


1 Answers

...why is the c => c. necessary? Wouldn't the following be understandable (by the compiler, and even more so by humans...

First off, if you prefer your queries to be readable by humans and elide the lambda then write your queries using the syntax that is readable by humans and elides the lambda:

query = from record in records 
        orderby record.DatePosted descending
        select record;

I prefer that syntax for the reasons you state: it's easier to read and it emphasizes the semantics of the query in the business domain rather than the fact that the ordering mechanism requires a key selection function.

Second, the c=>c. is not necessary. Suppose you have a method:

static DateTime DatePosted(Record record) { return record.DatePosted; }

Now it is perfectly legal to use the syntax you want:

records.OrderByDescending(DatePosted)

The compiler will deduce that DatePosted is the function to call to obtain the sort key and construct a delegate appropriately. (Note that it will also deduce the types correctly and work out that you meant OrderByDescending<Record, DateTime>.)

More generally though: a basic design principle of C# is that the language does not guess what you meant except in certain very well-defined situations(*). A query can be ordered by literally anything, and it is therefore beholden upon the author of the code to clearly state what the sort key is. In the query syntax, the range variables that represent elements of the collection are available so that you can easily expression "order by the date associated with each record". To just say "order by the date" would then involve making a guess.

For the lambda syntax, the method requires a function that selects the order key. You can supply the required a function by supplying a value of delegate type, a lambda convertible to a value of delegate type, or a method group convertible to a value of delegate type, as you see fit. A "naked" property is not a function.

So, could the C# language have been designed so that when you provide the name of a property without any context explaining what its a property of, that the compiler makes a guess? That it says "oh, I see there's a method called OrderBy here that takes a function and a sequence, let me make a guess that the name supplied for the function is intended to be the function "fetch this property off of a given element of the sequence"? Sure, I could have done that. The code is not that much harder to write. But that would not be in keeping with the design principles of the C# language. The benefit of saving a couple keystrokes is not worth the pain of violating the design principle that the intent is unambiguously stated in the code.


(*) Like implicitly typed locals, method type inference, implicitly typed arrays, and overload resolution, all of which involve the compiler making a best guess as to what the developer intended. The rules for making those guesses are carefully documented and have been designed so that most will bail out early if any ambiguity is detected.

like image 58
Eric Lippert Avatar answered Oct 12 '22 23:10

Eric Lippert