How to translate a lambda expression into English? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm a VB.NET programmer who also knows some C#. I've recently come across lambda expressions which in VB can look like this:
a = Function() b + c
However in C# they look like this:
a => b + c;
(Which, to me, looks a lot like a bizarre pointer expression from C)
The problem is that when reading C# code I mentally parse the operators into english words. So a = b + c; becomes "add b and c and assign to a". However I have no mental translation in my built in parser for the for the => operator yet so a => b + c; becomes either "a equals pointer to b and c" which makes no sense or "a is a lambda of b and c" which is dreadful.
I'm sure that the language creators meant for that operator to stand for a concept and that concept should be able to be reduced to a single word or very short phrase.
So what is the intended English translation for the => operator?
p.s. Note that I've tried to make the examples to be as simple as possible so as not to get bogged down in the specifics.

You have your example slightly wrong.
This VB code
a = Function()
Return b + c
End Function
looks like this in C#:
Func<int> a = () => b + c;
The problem with the suggestion of calling => "returns" is that this doesn't work with lambdas that don't return anything:
For example:
Action a = () => Console.WriteLine("Test");
If you call => "returns" in that scenario, it would be a bit confusing, I think.
Generally, the term used for => is "goes to" but some people say "maps to" or (in the case of lambdas that are used as predicates) "such that".
My personal preference is "maps to" (as suggested in the very first reply to the OP!).

How about 'a returns b plus c'?

In mathematics => symbol means Implies but for some reason c# calls this as Lambda operator. It will not be easy to read as a Lambda operatorb plus c
So you can simply call a implies b plus c

I always think "goes to" myself.

By definition in => is called lambda operator. Thy are used to separate inputs (on left) from the lambda body (on right). Your example do not stand for the same thing.
In your case more valid would be
a = delegate() { b + c };
that can be simplified using lambda to
a = () => b + c;
The lambda operator does not return anything, it more like "go to" or "use".

Take this example:
var person = GetRandomPerson();
string firstname = person.Select(a => a.FirstName);
I understand that it's syntactically difficult. But in this case, a is the person variable. Since you can choose that name freely in a lambda expression, it becomes easier to understand like this:
string firstname = person.Select(person => person.FirstName);
Keep in mind that there is no link between the person variable and the person lambda declaration (whatever it's called) . You can choose completely different names if you so choose.
The a or person part before the => is basically a declaration.
If you want it in words (like you asked): a => a.FirstName equates to "if my item were called 'a', then please give me the FirstName of 'a'"
This is what happens in a singular situation (i.e. there was only one person to select a field from).
Now what happens if you are holding a list of persons?
var persons = GetRandomPersons();
List<string> firstnames = persons.Select(a => a.FirstName);
If your base item (persons) is a collection of items, the a points toward each single object.
To make it more understandable:
List<string> firstnames = persons.Select(aSinglePerson => aSinglePerson.FirstName);
This code returns each person's FirstName. Assuming it's a string, this means that an IEnumerable<string> will be returned.
Think of it like doing the same with a foreach:
foreach (var aSinglePerson in persons)
{
var firstname = aSinglePerson.FirstName;
...
If you want it in words (like you asked): For multiple items, a => a.FirstName equates to "In this collection, sequentially take each individual item, call it 'a', and please give me the FirstName of 'a'"
I hope this explains the concept behind a lambda expression in C# syntax.

Related

Using ternary operator inside contains in lamba expression

I have a requirement to find records that does not contain value from studentids list. There is no 1:1 matching field. The records contain 3 key fields and based on condition, I have to compare against the studentids list.
For example: If rawdata record has non empty studentnumber value, then I have to concatenate studentnumber and sequencenumber and check if that combination exists in studentids list. Otherwise, I have to concatenate EnrollNumber and SequenceNumber.
I am trying to use ternary operator inside a contains as shown below,
var studentIDs = students.Select(x => x.StudentID).Distinct().ToList();
var rawData = StudentManager.GetAllData();
var resultList = rawData.Where(x => !studentIDs.Contains($"{(!string.IsNullOrWhiteSpace(x.StudentNumber)? (x.StudentNumber+x.SequenceNumber):(x.EnrollNumber+x.SequenceNumber))}")).ToList();
However, for larger dataset (more than 5K), it seems getting slower. Any suggestion for alternate method or way to improve will be greatly appreciated. Especially, if the code (Ternary operator) inside Contains can be simplified.
As #derpischer mention on the commend, Did you try with a HashSet?
Replace the firs line for the following:
var studentIDs = new HashSet<string>(students.Select(x => x.StudentID));
This will speed up your execution times. Please let me know if it works.
I think your approach to the logic is fine. I think you can present it in a clearer and easier way. Consider the below:
HashSet<string> studentIDs = students.Select(s => s.StudentID)
.ToHashSet();
string StudentID(RawDataStudent s) => string.IsNullOrWhiteSpace(s.StudentNumber)
? $"{s.EnrollNumber}{s.SequenceNumber}"
: $"{s.StudentNumber}{s.SequenceNumber}";
var rawData = StudentManager.GetAllData();
var resultList = rawData.Where(s => !studentIDs.Contains(StudentID(s)))
.ToList();
Important points:
Pulling the entire 'contains' lambda out and presenting it as a clearly named function with intent - good readability
Always try and work in the affirmative with booleans - specifically you ended up with this weird bracketed negation with the null or whitespace, just switch the returns around - again also easier to read
As other posters have commented, calling contains against a HashSet will be considerably faster
Note I've assumed your GetAllData return type somewhat - good example of when var is a bit evil

Why does Resharper suggest that I simplify "not any equal" to "all not equal"? [duplicate]

This question already has answers here:
LINQ: Not Any vs All Don't
(8 answers)
Closed 7 years ago.
I need to check whether an item doesn't exist in a list of items in C#, so I have this line:
if (!myList.Any(c => c.id == myID)))
Resharper is suggesting that I should change that to:
if (myList.All(c => c.id != myID)))
I can see that they are equivalent, but why is it suggesting the change? Is the first implementation slower for some reason?
The readability of the expression is to me a personal opinion.
I would read this
if (!myList.Any(c => c.id == myID)))
as 'is my item not in the collection'. Where this
if (myList.All(c => c.id != myID)))
reads as 'are all items in the collection different than my item'.
If the 'question' I want to ask -through my linq query- is 'is my item not in the list', then the first query better suits the question that I want to ask. The ! in front of the first query is not a problem.
It's all too easy to miss the ! at the start of the expression in your first example. You are therefore making the expression difficult to read. In addition, the first example reads as "not any equal to", whereas the second is "all not equal to". It's no coincidence that the easier to read code can be expressed as easier to read English.
Easier to read code is likely to be less buggy, as it's easier to understand what it does before changing it. It's because the second example is clearer that ReSharper recommends changing your code.
In general asking a positive question is more intuitive. If you asked the user "Do you really not want to delete this record?", guess how often he will hit the wrong button.
I personally like to turn constructs like this around:
// Not optimal
if (!x) {
A();
} else }
B();
}
// Better
if (x) {
B();
} else }
A();
}
An exception might be the test for not null where a != null might be perceived as positive.

What does this expression mean on the ipfiltering project?

I have seen the expression:
configuration.Filters.Select(f=> Create(f)).ToArray());
Im wondering what the f => Create(f) means? Is this a Lambda? And why is it in a Select clause?
Yes, this is a lambda expression. It's in a select clause as a projection. The lambda expression is executed for each item from configuration.Filters, and the result is then passed on to the next stage. It's hard to know exactly what that means in this case without knowing what Create does, but as an example, you might have:
int[] values = { 1, 2, 3 };
int[] squares = values.Select(x => x * x);
.ToArray();
// Now squares is { 1, 4, 9 }
This is part of LINQ (at least, I assume it is - it's just possible that you're calling a completely different Select method). LINQ is a big topic, but well worth exploring - fortunately there are plenty of tutorials and books around.
That's a lambda expression.
The Select extension method takes a delegate as a parameter.

Can someone explain it to me what closure is in real simple language ? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are ‘closures’ in .NET?
I am currently looking at lambda expression and the word closure keeps coming. Can someone explain it to me in real simple language.
I'd say this is a duplicate of: What are ‘closures’ in .NET?
"In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing."
Your shoes are in the hall; your
jacket is in the kitchen. Put them
on, and your gloves (they're in the
drawer), when going outside.
Now you can go playing with your cars.
At eleven o'clock you must go buy some
bread in the corner store.
Kid plays. Forgets all the world.
Alarm clock goes off; kid sees: eleven o'clock! Oh - go outside to buy bread using the "going outside" closure.
I like the Google example for Javascript (you can morph it for C# easily). It's not something a 5 year old would understand but then I doubt an average 5 year old would understand what a function was.
/*
* When a function is defined in another function and it
* has access to the outer function's context even after
* the outer function returns
* An important concept to learn in Javascript
*/
function outerFunction(someNum) {
var someString = 'Hai!';
var content = document.getElementById('content');
function innerFunction() {
content.innerHTML = someNum + ': ' + someString;
content = null; // IE memory leak for DOM reference
}
innerFunction();
}
The below answer was to the original wording which was akin to "How to explain closures to a 5-year old."
Take this box of legos; build yourself
a nice little space craft. When you go
to billy's house and bring your space
craft there; with closures you can
still can use all the pieces in your
box of legos, even though the box was left
in your bedroom.
If you really need to keep it simple, then a closure is a function with its context. The function in the closure can still access the same variables it could when it was defined, no matter where you call it from. (In Lua, these are called upvalues, which I think is a very descriptive term.)
I met the concept first in Lua, and this definition helped me understand the concept. Maybe have a look at Lua: its simpleness and power is fascinating, and certainly helps to develop a certain view at other languages. Its concept of closures would be a good example to that.
If the 5 year old knew C#, I would explain with this code sample:
int i = 0;
string result = null;
Action iExaminer = () =>
{
result = i % 2 == 1 ? "Odd" : "Even";
};
i = 1;
iExaminer();
Console.WriteLine(result);
If the 5 year old was learning linq, I would explain with this code sample:
string name = null;
IEnumerable<Customer> query = Customers.Where(c => c.Name == name);
name = "Bob";
// query is resolved when enumerated (which is now)
// Where will now call our anonymous method.
foreach(var customer in query)
{
Console.WriteLine(customer.Name);
}
Closure (computer science) says:
In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.
Translation:
Closures close/attach the variables around the function, so that that function can be teleported to somewhere else and still use those variables
e.g. suppose you are teleported to a remote location but have still access to your coffed mug lying on your table
Example:
function makefunc(x)
{
return function(){return x}
}
Now using makefunc, you can make many anonymous functions which will return what you pass to makefunc
So if you want a function which returns 10, use makefunc(10)(), though pretty useless way toget back 10 :)
When you know how to do something in general, you can specify some (or all) details and get a closure.
For example, you know how to buy ice-cream. Yyou know what to do if you will be in front of any shop. But if you want to go to a particular shop (for example, due to a Sunday discount), you move out of house with the aim of buying ice-cream there. "Buy some ice-cream at a store on the corner" is a closure of "buy some ice-cream". In fact, all these are closures of "buy some ice-cream somewhere":
Buy some ice-cream at the corner
Buy two ice-creams
Buy two ice-creams at the corner
Now go play with your friends, son! (and I bear in mind not say anything like that in front of the children)
This is a simple approach to the idea in C#: Closure

How do I pronounce "=>" as used in lambda expressions in .Net [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 2 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I very rarely meet any other programmers!
My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense.
So how do I say or read "=>" as in:-
IEnumerable<Person> Adults = people.Where(p => p.Age > 16)
Or is there even an agreed way of saying it?
I usually say 'such that' when reading that operator.
In your example, p => p.Age > 16 reads as "P, such that p.Age is greater than 16."
In fact, I asked this very question on the official linq pre-release forums, and Anders Hejlsberg responded by saying
I usually read the => operator as "becomes" or "for which". For example,
Func f = x => x * 2;
Func test = c => c.City == "London";
reads as "x becomes x * 2" and "c for which c.City equals London"
As far as 'goes to' - that's never made sense to me. 'p' isn't going anywhere.
In the case of reading code to someone, say, over the phone, then as long as they're a fellow C# programmer, I'd just use the word 'lambda' - that is, "p lambda p dot age greater-than sixteen."
In comments Steve Jessop mentioned 'maps to' in the case of transformations - so taking Anders' example:
x => x * 2;
would read
x maps to x times 2.
That does seem much closer to the actual intention of the code than 'becomes' for this case.
From MSDN:
All lambda expressions use the lambda
operator =>, which is read as "goes
to".
Reading Code Over the Telephone
From Eric Lippert:
I personally would say c=>c+1 as "see goes to see plus one". Some variations that I've heard:
For a projection, (Customer c)=>c.Name: "customer see becomes see dot name"
For a predicate, (Customer c)=>c.Age > 21: "customer see such that see dot age is greater than twenty-one"
I've always called it the "wang operator" :-)
"p wang age of p greater than 16"
I've seen people say, "Arrow."
I use "goes to" because a LINQ book told me to :)
How about "maps to"? It's both succinct and arguably more technically accurate (i.e. no suggestion of a state change as with "goes to" or "becomes", no conflation of a set with its characteristic function as with "such that" or "for which") than the other alternatives. Though if there's already a standard as the MSDN page appears to imply, maybe you should just go with that (at least for C# code).
"Maps to" is my preferred pronunciation. Mathematically speaking, a function "maps" its arguments to its return value (one might even call the function a "mapping"), so it makes sense to me to use this terminology in programming, particularly as functional programming (especially the lambda calculus) is very close to mathematics. It's also more neutral than "becomes", "goes to", etc., since it doesn't suggest change of state, as contextfree mentioned.
I haven't thought it about much, but I just succintly say "to". It's short and concise, and implies that the variable is passed to the expression. I suppose it could be confused with the numeral 2 ("two"), but I tend to pronounce "to" more like "ta" when speaking. Nobody (who knows lambdas, at least) has ever told me they thought it ambiguous...
// "Func f equals x to x times two"
Func f = x=> x * 2;
// "Func test equals c to c dot City equals London"
Func test = c => c.City == "London"
My short answer: "c 'lambda-of' e". Although I am clinging to "'lambda' c 'function' e", I think lambda-of is the ecumenical compromise. Analysis follows.
This is a great question if only for the bizarre answers. Most of the translations have other meanings than for lambda expressions, leading to exotic interpretations. As an old lambda-expression hacker, I just ignore the .NET notation and rewrite it as lambda in my head while wishing they had done almost anything else for this.
For narrating code over the phone, you want someone to be able to write the code down in sequence. That is a problem, of course, but lambda-arrow or something is probably the best you can get, or maybe lambda-in, but lambda-of is the most accurate.
The problem is the infix usage and how to name the whole thing and the role of the left and right parts with something that works when spoken in the infix place.
This may be an over-constrained problem!
I wouldn't use "such that" because that implies that the right hand side is a predicate that the left-hand side should satisfy. That is very different from talking about a right-hand side from which the left-hand side has been abstracted as a functional parameter. (The MSDN statement about "All lambda expressions" is simply offensive as well as inaccurate.)
Something rankles about "goes to" although it may be as close as we can get. "Goes to" implies a transformation, but there is not exactly some variable c that goes to an expression in c. The abstraction to a function is a little elusive. I could get accustomed to this, but I still yearn for something that emphasizes the abstraction of the variable.
Since the left-hand side is always a simple identifier in the cases used so far [but wait for extensions that may confuse this later on], I think for "c => expression" I would read "c 'lambda-function' expression"' or even "c 'arg' 'function' expression". In the last case, I could then say things like "b 'arg' c 'arg' 'function' expression".
It might be better to make it even more clear that a lambda-expression is being introduced and say something like "'arg' b 'arg' c 'function' expression".
Figuring out how to translate all of this to other languages is an exercise for the student [;<).
I still worry about "(b, c) => expression" and other variants that may come into being if they haven't already. Perhaps "'args' b, c 'function' expression".
After all of this musing, I notice that I am coming around to translating "c => e" as "'lambda' c 'function' e" and noticing that the mapping to exact form is to be understood by context: λc(e), c => e, f where f(c) = e, etc.
I expect that the "goes-to" explanation will prevail simply because this is where a dominant majority is going to see lambda expressions for the first time. That's a pity. A good compromise might be "c 'lambda-of' e"
If you imagine a lambda expression as the anonymous method that it is, "goes to" makes decent sense enough.
(n => n == String.Empty)
n "goes to" the expression n == String.Empty.
It goes to the anonymous method, so you don't have to go to the method in the code!
Sorry for that.
Honestly, I don't like to use "goes to" in my head, but I saw other people saying it seemed weird, and I thought I'd clear that up.
Apart from acquiring the preceding scope (all variables and constants that are in scope for a normal line of code at the point where a lambda expression occurs are available to the code of the expression) a lambda expression is essentially syntactic sugar for an inline function.
The list of values to the left of the production operator ("=>") contributes the structure and content of the stack frame used to make the call to this function. You could say that the list of values contributes both the parameter declarations and the arguments that are passed; in more conventional code these determine the structure and content of the stack frame used to make the call to a function.
As a result, the values "go to" the expression code. Would you rather say "defines the stack frame for" or "goes to" ? :)
In the narrowly defined application of boolean expressions used as filter conditions (a dominant use of lambda expressions extensively considered by other answers to this question) it is very reasonable to skip the method in favour of the intent of the code, and this leads to "for which" being just as succinct and saying more about the meaning of the code.
However, lambda expressions are not the sole province of Linq and outside of this context the more general form "goes to" should be used.
But why "goes to" ?
Because "populates the stack frame of the following code" is far too long to keep saying it. I suppose you could say "is/are passed to".
A crucial difference between explicitly passed parameters and captured variables (if I remember correctly - correct me if I'm wrong) is that the former are passed by reference and the latter by value.
Part of the problem is that you can read it out loud differently depending on how it's structured. It's a shame it's not as pretty or as integrated as ruby's |'s.
In Ruby, this same sybmol is called "hashrocket," and I've heard C# programmers use that term too (even though doing so is wrong).
My two cents:
s => s.Age > 12 && s.Age < 20
"Lambda Expression with parameter s is { return s.Age > 12 && s.Age < 20; }"
I like this because it reminds me of where lamdba expression comes from
delegate(Student s) { return s.Age > 12 && s.Age < 20; };
=> is just a shortcut so you don't have to use the delegate keyword and include the type info since it can be inferred by the compiler.
My term for => as applied to the examples shown result
'result = s => s.Age > 12 && s.Age < 20'
s where s.Age is greater than 12 and s.Age less than 20
'result = x => x * 2'
x where x is multiplied by 2
'result = c => c.City == "London"'
c where c.city is equivalent to "London"
'result = n => n == String.Empty'
n where n is an empty string

Categories

Resources