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

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

Related

Is there another "is" operator in C#? [duplicate]

This question already has answers here:
Why does is operator behave like == operator?
(3 answers)
Using "is" keyword with "null" keyword c# 7.0
(2 answers)
Closed 2 years ago.
I was teaching my students how to write a function. I used a simple algorithm to determine if a char value is an actual letter (and not a digit or something else).
So I actually typed what my student said (playing dumb on purpose): "if (letter is 'A') {...}"
To my surprise this didn't cause a compiler error. I added the same check for 'B' and 'C' and my program can now determine that A, B and C are indeed letters.
Why does that work? And WHAT exactly am I comparing here?
I'm not actively using type comparisons, which is what the internet keeps turning up.
I did an additional experiment with other values:
char l = 'A';
if (l is 'A')
{
Console.WriteLine("l 'A'...");
}
if (l is "A")
{
// Doesn't compile.
}
int x = 15;
if (x is 15)
{
Console.WriteLine("X is 15.");
}
if (x is 5.6)
{
// Also doesn't compile.
}
As far as I can tell "is" functions as an extended version of the equality (==) operator that also enforces the same type. But I can't find any documentation on it.
is might have two meanings, depending on which version of C# you have.
In older C# versions, is was short for "is assignable to" or "is assignable from", depending on how you read the code in your head. It wouldn't work for the code in your class because it expects a type on the right-hand side, but I include it here for completeness. It's also useful as an efficient and portable null check, ie variable is object is a better way to write variable != null1.
In newer C# versions, is can also be used for pattern matching. This was introduced in C# 72 and extended in C# 8, with more coming in 9. Specifically, the code in the question creates a Constant Pattern expression.
Here's another fun way to see this work. Coming in C# 9, instead of writing a check like this:
if (!string.IsNullOrEmpty(mystring))
You could instead write3
if (mystring is {Length:>0})
Which is nice because it's shorter and you could make an argument removing the negation makes it easier to understand.4
At least, according to one of the developers on the C# team at Microsoft. But what would he know? He only built the thing.
Really, C# 6 if you count exception filters.
Jared Parsons again.
I'd reject that argument on the grounds any gains in removing the negation are less than the subtlety introduced in how we validate for null. But you could try the argument ;) And before anyone asks, I have no idea at this time how the two options perform.

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

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.

Microsoft Solver Foundation Modulo Operator

I'm trying to add a basic constraint to my solver foundation by doing the following:
model.AddConstraint("c1", x % y == 0);
I get a compile error saying "Operator '%' cannot be applied to operands of type 'Microsoft.SolverFoundation.Services.Decision' and 'Microsoft.SolverFoundation.Services.Decision'".
This makes sense since a lot of operators aren't supported. However, a lot of the operators that aren't supported (sin, cos, tan, etc.) are available as specific methods on the Model class such as below:
model.AddConstraint("c1", Model.Sum(x,y) == 0);
If I replace "Sum" with "Mod", there is no method available.
Any ideas on how to perform a modulo operation in Solver Foundation? According to the documentation here, it is supported.
I am going to start using reflector to dig through the code, but I figured I would post it on here also. If I find a solution, I will update my question to include the answer.
Really interesting, I wanted to write the exact same question at SO :-)
I found out that a Mod operator is defined for the OML language at http://msdn.microsoft.com/en-us/library/ff818505(v=vs.93).aspx.
There is an overload of the AddConstraint method, that accepts an expression string(I guess an OML expression?) instead of the Term. Unfortunately, I don't know the right formatting, but once we get the knack out of it, we would be able to use all of the other operators as well.
EDIT
It looks like not every OML expression described in API is working. For example,
SolverContext sc = SolverContext.GetContext();
Model m = sc.CreateModel();
m.AddDecision(new Decision(Domain.IntegerRange(0,10), "a"));
m.AddDecision(new Decision(Domain.IntegerRange(0, 10), "b"));
m.AddConstraint(null, "a > 0");
m.AddConstraint(null, "b == Plus[a,2]");
The Plus[x,y] in this case is working and the solver computes the following decision
a: 1,
b: 3
But if I replace the last constraint with this one
m.AddConstraint(null, "b == Mod[a,2]");
I get an OmlParseException ("Failed to parse OML model. Expression: Mod[a,2]."). I guess we are on our own here and purhaps the best thing we can do is sticking with the answer of user141603.
I don't see Mod at http://msdn.microsoft.com/en-us/library/ff525341(v=vs.93).aspx, but here's a workaround:
Model.Floor(Model.Quotient(x,y))==Model.Ceiling(Model.Quotient(x,y))
This is only true if x/y is an integer, and so x%y==0.
There are also other ways of combining the allowed operators to check if it is divisible. My favorite (though I wouldn't recommend it because of floating point precision) is
Model.Sin(Math.PI*Model.Quotient(x,y))==0

Dynamically evaluating statement with multiple equality operators

I've seen quite a few expression parsers / tokenizers that can take a certain string and evaluate the result. For example, you could pump the string:
4+4
into the following code:
MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
//' You always need to initialize a language engine
sc.Language = "VBScript";
//' this is the expression - in a real program it will probably be
//' read from a textbox control
string expr = "4+4";
double res = sc.Eval(expr);
and get 8. But, is there a parsing tool out there that can evaluate the string:
4 = 4 = 4
? So far, all examples fail with an error of not being able to compare a double and boolean (which makes sense from a compilers perspective, but from a human perspective, we can see that this is true). Anyone come across something that can achieve this?
From a human perspective, this is only true if we think of x = y = z as a special operator (with three operands), where it implies x = y, y = z, x = z. That is a specific syntactical interpretation of the expression. A human (particularly a programmer) could also interpret it the same way most compilers do, which is to choose the left-most grouping ( x = y ) and then compare the result of that comparison (a boolean value) to z. Even to a human, this doesn't make sense under this syntax. It only seems obvious from a human perspective because humans are notoriously fuzzy when it comes to choosing a syntax that 'makes sense' for a given context.
If you really want that level of 'fuzziness', you'll need to look into something like Wolfram Alpha, which performs contextual analysis to try to find a best guess for the meaning of the expression. If you enter '4 = 4 = 4' there, it will reply True.
You need to define syntax for your "language" and build parser as your expected behavior is not covered by normal expression syntax (and also normal languages should evaluate it to "false" as every language I heard of implements = as binary operation and hence will endup with "4 = true" at some point). There are tools to build parser for C#...
Side note: to match "a human perspective" is insanely hard problem still not solved even for human to human communication :).
try with
var result = (int) HtmlPage.Window.Eval("4 + 4");

Is the from keyword preferable to direct method calls in C#?

Of these two options:
var result = from c in coll where c % 2 == 0 select c;
var result = coll.Where ( c => c % 2 == 0 );
Which is preferable?
Is there any advantage to using one over the other? To me the second one looks better, but I would like to hear other people's opinions.
If you've only got one or two clauses, I'd go for "dot notation". When you start doing joins, groupings, or anything else that introduces transparent identifiers, query syntax starts to appeal a lot more.
It's often worth trying it both ways and seeing what's the most readable for that particular situation.
In terms of the generated code, they'll be exactly the same in most cases. Occasionally there'll be an overload you can use in dot notation which makes it simpler than the query expression syntax, but value readability over everything else in most cases.
I also have a blog post on this topic. I would definitely recommend that developers should be comfortable with both options - I'd be quite concerned if a colleague were using LINQ but didn't understand the fundamentals of what query expressions were about, for example. (They don't need to know every translation involved, but some idea of what's going on will make their lives a lot easier.)
I always use the lambda syntax because to me it's clearer what's actually happening and it looks cool to boot. But we have some devs here that always do the opposite (sql nerds I guess :) Fortunately, tools like ReSharper can just transform between the two with a click.

Categories

Resources