Wednesday, September 24, 2008

Birthday Cakes For Cyclists

Footsteps to Lamba Expressions

lambda expressions are one of the new features that includes the C # compiler (Visual Basic 9 also has), but to understand that they are treated and that we can help, first let's make a little history and understand that the delegates and anonymous methods.

Delegates, the first step

The delegates play an important role within himself. NET Framework and the applications developed with it, in this sense we can see, for example, as an application of Events delegates. But rather than the delegates, without the slightest hint of being rigorous and very personal way to define a delegate gives us a mechanism that serves as a reference (type-safe) to a method. When you declare a delegate, just declare the method signature without any implementation. The delegate has a name and can be referenced like any other. Now when you declare a method whose signature matches the signature of the delegate declared this method can be passed as a parameter to any method that references to the delegate. This essentially gives us an alternative form of polymorphism. Sounds complex is not so in reality we see something more tangible.
Suppose the following problem: a football team calculated points obtained after 5 dates of a tournament in Scheme 2 points for victory, 1 point for a draw and 0 for tracks, but also want to calculate the points earned by the scheme that gives 3 points to victories instead of 2.
models to the team leaving and then follows the method responsible for calculating points



public class Team {
string _name;
_resultados IList;
_puntos int;

public Team (String name) {

_name = name;}


public string Name {get {return _name
;} set {_name =
value;}}

results
public IList {get {return
_resultados;} set {
_resultados = value;}}


points {public int
_puntos get {return;}}

/ / TODO: public CalcularPuntos void ()}


Before Implementing the method CalcularPuntos () declare our delegate: public delegate int
ActualizarEquipo (char character);
But we have our delegate, or declare a signature of a method and ActualizarEquipo name
Now let us look at this statement I make using the keyword delegate, this statement sets the delegate returns an int and receives as a parameter an object of type Task. Any of the following methods consistent with the definition of my delegation:

ContarVictorias int (char character);
ContarEmpates int (char character);

However, any of the following do not match: Team

Pointer (IList listaEquipos) ;
double Average (Equipment);

Now we have declared our delegate and know when a method is consistent with it we can see how to use it in our small example. Our representative will assist us to implement the desired behavior to calculate the points with two different strategies. First full
CalcularPuntos method class public void

Team CalcularPuntos (ActualizarEquipo Updater) {

_puntos = 0;
if (_resultados! = null & & _resultados.Count> 0)
foreach (char character in _resultados)
_puntos + = Updater (character);}

full
This team model.
Then I will implement two methods trivial to implement the two strategies have

points CalcularPuntos_2_1_0 static int (char character)

{switch (character)

{case 'w': return
2;
case ' d ':
return 1;}

return 0;}

CalcularPuntos_3_1_0 static int (char character)

{switch (character)

{case 'w': return
3;
case 'd':
return 1;

} return 0;}


Then I perform a test of it all together with a small console application and two teams that will upload the code

static void Main (string [] args) {

/ / load Team
ComputerA two teams = new Team ("Team"); \u200b\u200b
equipoA.resultados = new List {'w', 'w', 'l', 'l', 'd'};

EquipoB team = new Team ("Team B");
equipoB.resultados = new List {'w', 'l', 'd', 'd', 'd'};

listaEquipos List = new List { ComputerA, equipoB};

/ / Calculating using
2_1_0 Console.WriteLine ("Points per team with the scheme \\ nVictoria = 2 points \\ nEmpate = 1 point \\ n");
CalcularPuntosYMostrar (listaEquipos, CalcularPuntos_2_1_0)

/ / Calculating using
3_1_0 Console.WriteLine ("\\ n \\ nPuntos per team with the scheme \\ nVictorio = 3 points \\ nEmpate = 1 point \\ n");
CalcularPuntosYMostrar (listaEquipos, CalcularPuntos_3_1_0)

/ / wait for user entry
Console.WriteLine ("Press enter key
..."); Console.ReadLine ();}
static void
CalcularPuntosYMostrar (IList equipment ActualizarEquipo updater)

{foreach (eq Team in teams) {

eq . CalcularPuntos (updater);
Console.WriteLine ("{0}: {1} point (s)", eq.Nombre, eq.puntos.ToString ());

}}

Here's the result



The code we use to test our first delegate is fairly simple and created two new teams complete the list of results with the results of matches after five dates. The "magic" occurs when calculating the points for each team, use the delegate as a type parameter that I can pass allows me to create a setting that looks like a pointer or reference to a method, however it is neither as in C # a delegate is an object that inherits from System.Delegate. C # 3.0 compiler performs the "magic" (in C # 2.0 syntax was different, because it was necessary to create an instance of the delegate). Methods

Anonymous (second step)

far our delegation has been helpful but we still have one step to the final approach to lambda expressions, let us return to our example and say now we want to add a new feature for a computer to calculate the number of wins and draws, as I quoted above methods may be as follows int

ContarVictorias (char character);
ContarEmpates int (char character);
Consider how to implement
fucionalidad following, adding the two previous methods that match my delegate

ContarVictorias static int (char character)

{if (character == 'w')
return 1;
return 0;}

ContarEmpates static int (char character)

{if (character == 'd')
return 1;
return 0;}


Then we can proceed as follows: Static int

ContarResultados (IList result ActualizarEquipo updater)

{int count = 0;
foreach (char character in result) {

updater count + = (character);

} return count;}


And in the Main ...

/ / Calculating Victorie
Console.WriteLine ("\\ nVictorias");
foreach (eq Team in listaEquipos)
Console.WriteLine ("{0} {1} win game (s)", eq.Nombre, ContarResultados ( eq.resultados, ContarVictorias). ToString ());

So far nothing new but as we see the same thing with an anonymous method, anonymous methods is a mechanism implemented in C # 2.0, which allows me to make a statement in line for a method using the delegate keyword and a code block to see how we do count the ties:

/ / Calculating drwa
Console.WriteLine (" \\ nEmpates ");
foreach (eq Team in listaEquipos)
Console.WriteLine (" {0} {1} tied game (s) "
, eq.Nombre
, ContarResultados (eq.resultados,
delegate (char character)

{if (character == 'd')
return 1;
return 0;}
). ToString ());

Well that does not make our code more readable, right? This type of statement anonymous methods I reserve it for cases where it really is convenient. (VB. NET 8.0 does not support the use of anonymous methods.)

Here is where you come into play Lambda Expressions, which make the creation of delegates is much more readable and concise.

In C # Programming Guide on MSDN:

" A lambda expression is an anonymous function that can contain expressions and instructions and can be used to create delegates or expression tree types. "

Here's how our code is to have ties using lambda expressions:

/ / Calculating drwa
Console.WriteLine (" \\ nEmpates ");
foreach (eq Team in listaEquipos)
Console.WriteLine ("{0} {1} tied game (s)"
, eq.Nombre
, ContarResultados (eq.resultados,
c => {if (c == ' d ') return 1; return 0;}). ToString ());

see the expected result



This really is much more readable than before. The highlighted part in both is exactly snippets I've only changed the syntax. Highlight the following aspects of these expressions:

• If the lambda expression is one line I can do without the return keyword.
• The C # compiler infers the return type involved in the expression and lambda expressions are always assigned to a delegate the compiler looks for the expected type of the delegate and use this when you validate your code.

LINQ and Lambda Expressions, the next step

Lambda expressions are a concise and readable to define delegates. These expressions can be widely used in LINQ. The vast majority of the delegates used methods of LINQ I can sort, filter and take concrete actions on collections of objects.
We refer back to C # Programming Guide on MSDN, we find
"When you use the method syntax to call the Where method on the Enumerable class (such as is done in LINQ to Objects and LINQ to XML), the parameter is a delegate type. A lambda expression is the most practical way to create such a delegate. When you call the same method, for example, Queryable ..::. System.Linq class (as in LINQ to SQL), the parameter type is System.Linq.Expressions ..::. Expression, where Func Func is a delegate that has five input parameters. Again, a lambda expression is a very concise way to build the expression tree. Lambda expressions allow calls to Where may look similar, but in fact, the type of object created from the lambda expression is different. "
Well here we can as you can see the Lambda Expressions are one of the new features of the compiler C # 3.0 that are going to be very useful when working with delegates for example if we have to pass parameters of such functions LINQ.
Well this is the first post in my blog and I hope it will be useful to someone, the idea will be today and always convey a bit of how much I learn every day, in my college work or did not, in life same.
Greetings.

0 comments:

Post a Comment