Advice on lambda expression [duplicate] - c#

This question already has answers here:
Where do I use delegates? [closed]
(8 answers)
Closed 7 years ago.
Say that I have this line of code:
Action<int> square = number => Console.WriteLine(number * number);
Though I understand that it is handy to create a method on the fly, if you only need to call the lamda expression once, does it gain any perfomance by doing so?
In addition, let's say I do something more with the value before the WriteLine:
Action<int> square = number => {
number += 10;
Console.WriteLine(number * number);
};
I could just solve this very simple by adding 10 to number and then do number * number without the lambda expression. Can anyone give me a good example/situation when to use this expression?

I understand that it is handy to create a method on the fly, using lambda, if you only need to call it once but do I gain any perfomance by doing so?
Delegates (such as instances of Action<T>) are one level of indirection (very similar to virtual method dispatch); the runtime does not just execute the code inside the method when you invoke the delegate; the runtime will first have to figure out what method they reference, then invoke that method.
Delegates certainly don't speed things up. But then you should state what we are comparing them against.
That being said, the minute overhead of delegate dispatch is generally negligible in all but the most extreme scenarios; don't worry too much about the performance of delegate invocation.
Action<int> square = number =>
{
number += 10;
Console.WriteLine(number * number);
};
Can anyone give me a good example/situation when to use this expression?
I would not mutate arguments if I could just as well write the code another way; all the more so when we are talking about a lambda's parameter. I would instead put the value derived from the argument into a (temporary) local variable:
Action<int> square = number =>
{
int n = number + 10;
Console.WriteLine(n * n);
};
The code is not really any longer, and generally easier to understand because you don't have to worry about your lambda accidentally changing an object passed to it.

Imagine the following:
You have list of values where you want to apply a function. You can save this function in an Action and later apply this function in your code.
E.g:
Predicate<int> isEven = number => number % 2 == 0;
List<int> numbers = Enumerable.Range(1,100);
var evenNumbers = numbers.Where(isEven);
This is more reusable and more readable than a foreach loop.

Related

Arguments passed "by name" in C#

The Scala programming language has a neat feature, called pass by name arguments, that allows some arguments to only be evaluated if required.
For example, it's possible to write a while loop using a curried method such as the following:
// This is Scala code. A simulated while loop
#scala.annotation.tailrec
def myWhile(condition: => Boolean)(actions: => Unit): Unit = {
if(condition) {
actions
myWhile(condition)(actions)
}
}
This method can be used like a regular while loop, thanks to Scala's syntactic sugar, closures and—of particular interest here—the ability to pass expressions as function arguments, which are evaluated when referenced (as indicated by the : => type argument declaration).
For example, the following prints "Hello!" to the console ten times:
var i = 0
myWhile(i < 10) {
println("Hello!")
i += 1
}
For those who need to understand what is happening, the expression i < 10 is evaluated each time condition appears inside the if(...) statement inside the method, similarly, println("Hello!"); i += 1 is evaluated each time actions appears in the body of the method. When recursively calling myWhile for the next iteration, the expressions are passed as is, since the method requires expressions, not values. Scala terms these pass by name arguments.
If these arguments were passed by value instead, then i < 10 would be passed to myWhile as false, while "Hello!" would be printed exactly once, i would be incremented once, and the loop would execute infinitely.
(Scala is primarily a functional language, and this code is not even close to being FP, but it's a simple example.)
My question is, is there a way to pass arguments in this way to a C# function? Also note that I'm restricted to using C# 7.3. :-(
It sounds like you can get somewhat close with Func`1 and Action:
void MyWhile(Func<bool> condition, Action action) {
while (condition()) {
action();
}
}
and calling as:
int i = 0;
MyWhile(() => i < 10, () => {
Console.WriteLine("Hello!");
++i;
});
The syntax is a bit different, but the idea is similar.

What are delegates for? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the advantages of delegates?
I have created a sample application. I am really finding it difficult to understand why to use delegates because without delegates we can achieve everything .
class Program
{
public delegate double Integrand(double x);
static double MyFunc1(double x) { return x + 10; }
static double MyFunc2(double x) { return x + 20; }
public static double Gauss3DelMethod(Integrand f)
{
double a = f(1);
return a;
}
public static double Gauss3SimpleMethod(double x)
{
double a = x;
return a;
}
static void Main(string[] args)
{
//with delegates
double res = Gauss3DelMethod(MyFunc1);
double res1 = Gauss3DelMethod(MyFunc2);
//without delegates
double res2 = Gauss3SimpleMethod(MyFunc1(1));
double res3 = Gauss3SimpleMethod(MyFunc2(1));
int i = 0;
}
}
So, why should I use delegates?
In your particular example, maybe it's not important. (It's not clear what it's trying to achieve.)
But suppose you wanted to make the method execute the same MyFunc1 or MyFunc2 for several different inputs. For example, suppose you were implementing the Newton-Raphson method, to operate over a general function. In that situation, you couldn't call the function once and pass that into the method - you want to pass the actual function into the method, so that the method can call it with whatever inputs it needs.
A similar example is sorting. For example, using LINQ you can write something like:
var sorted = people.OrderBy(x => x.Age).ToList();
There we're passing a function to project each source element to the ordering key. We don't have to execute that function ourselves - OrderBy will do it for us (lazily).
Of course, all of this can be done with single-method interfaces too - delegates and single-method interfaces have a lot in common. However, delegates have the following benefits over single-method interfaces:
Delegates are multi-cast - they can be combined/removed, usually for the sake of events
You can execute them asynchronously with BeginInvoke/EndInvoke
You can build them with anonymous methods and lambda expressions
You can represent logic as data via expression trees using lambda expresions; these can then be compiled into delegates
You can build a delegate from any method with the appropriate signature - so for example a single class can have multiple methods "implementing" the same delegate type, whereas you can't implement an interface multiple times in one class
Likewise delegate implementation methods can be private, whereas interface methods have to be public (or somewhat-public via explicit interface implementation)
All of these could have been addressed differently using single-method interfaces, of course, but delegates are a handy alternative.
In conclusion: delegates are very useful. Just because you've written some trivial code which doesn't particularly require them doesn't mean they're not useful. I would strongly suggest you look into LINQ, event handlers and the TPL, all of which use delegates heavily.
Delegates are a useful way to pass around functions.
Func and Action are also delegates. Without them you couldn't use almost every LINQ method and, beginning from C# 3.0, you can use Lambda Expressions to create them faster.
Imagine for example you have an enumerable of integers:
var numbers = Enumerable.Range(0, 100);
By using delegates you can create higher-order functions (http://en.wikipedia.org/wiki/Higher-order_function) that can help you to filter, for example, the numbers above in several ways. Where is one of the cases.
You may want to select just odd numbers:
var odd = numbers.Where(a => a % 2 == 0);
Or even ones:
var even = numbers.Where(a => a % 2 != 0);
Without them you would have to create a method for each filter (e.g. WhereOdd or WhereEven)

How does a lambda in C# bind to the enumerator in a foreach?

I just came across the most unexpected behavior. I'm sure there is a good reason it works this way. Can someone help explain this?
Consider this code:
var nums = new int[] { 1, 2, 3, 4 };
var actions = new List<Func<int>>();
foreach (var num in nums)
{
actions.Add(() => num);
}
foreach (var num in nums)
{
var x = num;
actions.Add(() => x);
}
foreach (var action in actions)
{
Debug.Write(action() + " ");
}
The output is a bit surprising for me:
4 4 4 4 1 2 3 4
Obviously there's something going on with how the lambda is referencing the enumerator. In the first version of the foreach, is 'num' actually bound to 'Current', instead of the result returned by it?
This is well-known and established behavior regarding lambdas, though frequently surprising to those who've encountered it for the first time. The fundamental issue is that your mental model of what a lambda is isn't quite correct.
A lambda is a function that doesn't get run until it's invoked. Your closure binds a reference to that lambda instance, not the value. When you execute your actions in your final foreach loop, that's the first time you're actually following the closed reference to see what it is.
In the first case, you're referencing num, and at that point, the value of num is 4, so of course all your output is 4. In the second case, each lambda has been bound to a different value that was local to the loop each time, and that value isn't changed (it hasn't been GC'd solely because of the lambda reference.) therefore, you get the answer that you expect.
The closure over a local temporary value is actually the standard approach to capture a specific value from a point in time within the lambda.
Adam's link to Eric Lippert's blog provides a more in-depth (and technically accurate) description of what's going on.
See Eric Lippert's blog post on this issue; it has to do with how iterator variables are scoped in code, and how that applies to lambda closures and hoisted functions.
Since the foreach construct is just syntactic sugar it is best to think of it in it's true form.
int num;
while (nums.MoveNext())
{
num = nums.Current;
actions.Add(() => num);
}
The lambda will capture the num variable so when you execute the lambda the latest value of num will be used.
This is because of two following things:
1) delegates save context (scope) of outside variables
2) first foreach cycle will compile in only one "num" variable declared.
3) lazy evaluation
Each delegated added in the first cycle will save the same num variable saved to the scope. Because of lazy evaluation you will run the delegates after the first cycle is finished, so num veraible, saved to the delegates' scope equals 4.
See On lambdas, capture, and mutability

Functors when should I use them whats their intended use [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I Just can't seem to wrap my head around them.
As I understand it's dynamically adding logic to a class. Are classes within the framework prepared for this?
Why should I just extend the class and add the functionality to it in the extension. I would be globally accessible and afaik much easier to maintain.
I've Read there are 4 functor types:
Comparer
Closure
Predicate
Transformer
We should probably Handle each one of them.
p.s. is there something like it in vb?
So I can state I think that lambda expressions are functors. This clears up things for me a bit :) (hehe)
Lambda expressions are functors?
Anonymous functions are functors?
But I asked this question because I ran into another type of fucntors namely these ones:
delegate void FunctorDelegate(int value);
class Addition {
FunctorDelegate _delegate;
public Addition AddDelegate(FunctorDelegate deleg) {
_delegate += deleg;
return this;
}
public int AddAllElements(IList< int> list) {
int runningTotal = 0;
foreach( int value in list) {
runningTotal += value;
_delegate(value);
}
return runningTotal;
}
}
And then calling it with this:
int runningTotal = new Addition()
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 1) {
runningOddTotal += value;
}
}))
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 0) {
runningEvenTotal += value;
}
}))
.AddAllElements(list);
So no fancy lambda style things.
Now I have this example but it isn't at all clear why this is a "good" solution.
Are delegates (functors) used as lambda expressions or anonymous methods "in most cases" just there as a shortcut for the programmer? There are as far as I can see only a few cases where they're actually the prefered choice for a problem.
I think you're confusing terms from different languages. You seem to be using "Functor" in the C++ or Java sense, e.g. see the wikipedia page. In C++, it's an object of a class that overloads the function-call operator, so it can be used as a function but with state.
This is logically the same thing as a delegate bound to an instance method in C# (or any .NET language).
There are three ways to write such a thing. First, you can write an ordinary method, and then assign the name of the method to a delegate variable.
void MyMethod() { Console.WriteLine("Hi!"); }
void Foo()
{
Action a = MyMethod;
a();
}
Second, you can use anonymous method syntax, introduced in C# 2.0:
void Foo()
{
Action a = delegate { Console.WriteLine("Hi!"); }
a();
}
Thirdly, you can use lambda syntax, introduced in C# 3.0:
void Foo()
{
Action a = () => Console.WriteLine("Hi!");
a();
}
The advantage of the last two is that the body of the method can read and write local variables in the containing method.
The advantage of lambda syntax over anon-methods are that it is more succinct and it does type inference on parameters.
Update: The advantage of anon-methods (delegate keyword) over lambdas is that you can omit the parameters altogether if you don't need them:
// correct way using lambda
button.Click += (sender, eventArgs) => MessageBox.Show("Clicked!");
// compile error - wrong number of arguments
button.Click += () => MessageBox.Show("Clicked!");
// anon method, omitting arguments, works fine
button.Click += delegate { MessageBox.Show("Clicked!"); };
I know of only one situation where this is worth knowing, which is when initializing an event so that you don't have to check for null before firing it:
event EventHandler Birthday = delegate { };
Avoids a lot of nonsense elsewhere.
Finally, you mention that there are four kinds of functor. In fact there are an infinity of possibly delegate types, although some authors may have their favourites and there obviously will be some common patterns. An Action or Command takes no parameters and returns void, and a predicate takes an instance of some type and returns true or false.
In C# 3.0, you can whip up a delegate with up to four parameters of any types you like:
Func<string, int, double> f; // takes a string and an in, returns a double
Re: Updated Question
You ask (I think) if there are many use cases for lambdas. There are more than can possibly be listed!
You most often see them in the middle of larger expressions that operate on sequences (lists computed on-the-fly). Suppose I have a list of people, and I want a list of people exactly forty years old:
var exactlyForty = people.Where(person => person.Age == 40);
The Where method is an extension method on the IEnumerable<T> interface, where T in this case is some kind of Person class.
This is known in .NET as "Linq to Objects", but known elsewhere as pure functional programming on sequences or streams or "lazy" lists (all different names for the same thing).
In .NET terms, I think what you are describing is the Delegate - and it exists in all of .NET, not just C#.
I'm not sure that a "closure" would a "type" in the same was as a comparer/predicate/transformer, since in C# terms a closure is simply an implementation detail but can be any of those three.
In .NET, delegates are used in two main ways:
as the eventing mechanism
to provide functional-style programming
The first is important, but it sounds like you are more interested in the second. In reality, they operate much like single-method interfaces... consider:
List<int> vals = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenVals = vals.FindAll(i => i % 2 == 0); // predicate
List<string> valsAsStrings = vals.ConvertAll(i => i.ToString()); // transformer
// sort descending
vals.Sort((x, y) => y.CompareTo(x)); // comparer
A closure is more where we bring additional scope from outside the delegate into the delegate:
int max = int.Parse(Console.ReadLine()); // perhaps 6
List<int> limited = vals.FindAll(i => i <= max);
here the max is captured into the delegate as a closure.
Re "Are classes within the framework prepaired for this?" - many are, and LINQ goes a long way to allowing this even wider. LINQ provides extension methods over (for example) all of IEnumerable<T> - meaning that collections without delegate-based access aquire them for free:
int[] data = { 1,2,3,4,5,6,7,8,9 };
var oddData = data.Where( i => i % 2 == 1 );
var descending = data.OrderBy(i => -i);
var asStrings = data.Select(i => i.ToString());
Here the Where and OrderBy methods are LINQ extension methods that take delegates.
Interesting with terminology; my spontaneous interpretation of the term "Functor" was that it referred to anonymous methods. So that will be my take on it.
These are some of my typical uses:
Comparisons (usually for sorting a list):
List<int> ints = new List<int>();
ints.AddRange(new int[] { 9, 5, 7, 4, 3, 5, 3 });
ints.Sort(new Comparison<int>(delegate(int x, int y)
{
return x.CompareTo(y);
}));
// yes I am aware the ints.Sort() would yield the same result, but hey, it's just
// a conceptual code sample ;o)
// and the shorter .NET 3.5 version:
ints.Sort((x, y) =>
{
return x.CompareTo(y);
});
I will use this approach for comparisons, rather than having it in its own method an using a delegate for that method, in the cases where this particular sort happens in one place only. If it is likely that I will want to use the same comparison somewhere else, it gets to live in its own, reusable method.
Another of my fairly common uses is in unit testing, when the test relies on some event being raised. I have found that to be essential when unit testing workflows in Workflow Foundation:
WorkflowRuntime runtime = WorkflowHost.Runtime;
WorkflowInstance instance = runtime.CreateWorkflow(typeof(CreateFile));
EventHandler<WorkflowEventArgs> WorkflowIdledHandler = delegate(object sender, WorkflowEventArgs e)
{
// get the ICreateFileService instance from the runtime
ISomeWorkflowService service = WorkflowHost.Runtime.GetService<ISomeWorkflowService>();
// set the desired file content
service.DoSomeWork(instance.InstanceId, inputData);
};
// attach event handler
runtime.WorkflowIdled += WorkflowIdledHandler;
instance.Start();
// perform the test, and then detach the event handler
runtime.WorkflowIdled -= WorkflowIdledHandler;
In this case it is simpler to have the event handler declared as anonymous methods since it uses the instance variable that is defined in the unit test method scope. Had I intstead opted to implelment the event handler as its own separate method I would also need to figure out a way for it to pick up instance, probably by introducing a class level member, which would not seem like a perfect design in a unit test class.
There are more cases where I find this in my code, but they usually have one or two things in common:
I have no interest in referencing that piece of code from anywhere else than in that particular place.
The method needs access to data that would be out of the scope for a regular method
The real answer is that a functor is a type of mathematical object, and is "reified" by different languages in different ways. For example, suppose that you have a "container" object that stores a bunch of other objects of the same type. (For example, a set or array) Then, if your language had a method that let you 'map' over the container, so that you could call a method on each object in the container, then the container would be a functor.
In other words, a functor is a container with a method that lets you pass a method to its contained things.
Every language has its own way of doing this, and they sometimes conflate the usage. For example, C++ uses function pointers to represent the "passing in" of a method, and calls the function pointer a "functor." Delegates are just a handle on methods that you can pass in. You are using the terminology "incorrectly", just like C++ does.
Haskell gets it right. You declare that a type implements the functor interface, and then you get the mapping method.
Functions (like lambdas) are functors too, but it can be kind of hard to think of a function as a "container". In short, a function is a "container" around a return value, constructed in such a way that the return value (possibly) depends on the function's arguments.
I'm sure you mean Lambda Expressions. Those are Small Functions you can write very quickly, and they have the characteristic "=>" Operator. These are a new Feature of C# 3.0.
This Example will be a classic Transformer; to use one we need a delegate to define the signature for the Lambda Function.
delegate int Transformer(int i);
Now Declare a Lambda with this delegate:
Transformer sqr = x => x * x;
We can use it like a normal function:
Console.WriteLine(sqr(3)); //9
These are used in LINQ Queries a lot, for example to Sort (Comparer), to Search through (Predicate).
The book "C# Pocket Reference" (apart from beign the best around in my opinion, has a very good part on Lambdas. (ISBN 978-0-596-51922-3 )

Closures for anonymous methods in C# 3.0

Why do closures exist for anonymous methods? Why not just pass state into the method without the overhead of a new class being generated with the closure variables being copied in? Isn't this just a throwback to "making everything global?"
Someone talk me down, I feel like i'm missing something here...
Purely, convenience... you don't know how much state you are going to need when defining, for example, a Predicate<T> - consider:
List<int> data = new List<int> {1,2,3,4,5,6,7,8,9,10};
int min = int.Parse(Console.ReadLine()), max = int.Parse(Console.ReadLine());
List<int> filtered = data.FindAll(i => i >= min && i <= max);
here we've passed two additional bits of state into Predicate<T> (min and max) - but we can't define List<T>.FindAll(Predicate<T>) to know about that, as that is a caller detail.
The alternative is to write the classes ourselves, but that is hard, even if we are lazy:
class Finder {
public int min, max;
public bool CheckItem(int i) { return i >= min && i <= max;}
}
...
Finder finder = new Finder();
finder.min = int.Parse(Console.ReadLine());
finder.max = int.Parse(Console.ReadLine());
List<int> filtered = data.FindAll(finder.CheckItem);
I don't know about you, but I prefer the version with the closure... especially when you consider how complex it gets when you have multiple contextual levels. I want the compiler to worry about it.
Consider also how often you use such constructs, especially for things like LINQ: you wouldn't want to have to do it any other way...
The overhead of creating a new class probably isn't something to worry about. It's just a convenient way for the CLR to make bound variables (those captured by the closure) available on the heap. They are still only accessible within the scope of the closure, so they're at all not "global" in the traditional sense.
I believe the reason for their existence is mainly convenience for the programmer. In fact, it's purely that as far as I'm concerned. You could emulate the behaviour of a closure pretty well before they existed in C#, but you don't get any of the simplicity and syntactical sugar that C# 3.0 offers. The entire point about closures is that you don't need to pass the variables in the parent scope to the function, because they're automatically bound. It's much easier and cleaner for the programer to work with, really, if you consider that the alternative is true global variables.
At least one thought is that closures exist in other languages such as javascript. So they probably included closures to be in line with people's prior experience with anonymous methods.
Because you take write this:
var divsor = [...]
for(int x = 0; x < 10000000; x++){
source[x] = source[x] / divsor
}
And easily turn it into this
var divsor = [...]
Parallel.For(int x = 0; x < 10000000; x++, ()=> {
source[x] = source[x] / divsor
})
Some methods require a specific signature. For example:
public void set_name_on_click(string name)
{
button.Click += (s,e) => { button.Text = name; };
}
A full closure solves this very neatly. You really don't want to mess with the anonymous methods signature.
Because the CLR takes care of it, the easiest way to "pass state into the method" is to auto-generate a class, which encapsulates that state.

Categories