C# notation understanding Select(int.Parse) - c#

I found a little script that I understand fully. I've got a string with "1 -2 5 40" for example. It reads the input string, splits it into a temporary array. Then this array is parsed and each element is transformed into an integer. The whole thing is order to give the nearest integer to zero.
But what I don't understand is the notation Select(int.Parse). There is no lambda expression here and the method int.Parse isn't called with brackets. Same with the OrderBy(Math.Abs)
Thank you in advance =)
var temps = Console.ReadLine().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);
var result = temps.Select(int.Parse)
.OrderBy(Math.Abs)
.ThenByDescending(x => x)
.FirstOrDefault();

int.Parse is a method group - what you're seeing is a method group conversion to a delegate. To see it without LINQ:
Func<string, int> parser = int.Parse;
int x = parser("10"); // x=10
It's mostly equivalent to:
Func<string, int> parser = text => int.Parse(text);
... although there are plenty of differences if you want to go into the details :)

Select(int.Parse) is nearly equivalent to Select(x => int.Parse(x)).
The Select demands an Func<T, R>, which in this case is also the signature of int.Parse (it has a single parameter with a return value). It convers the method group to the matching delegate.
In this case Func<T, R> will map to Func<string, int>, so it matches the int Parse(string) signature.

int.Parse is a method with signature string -> int (or actually, a method group, with different signatures. But the compiler can infer you need this one, because it is the only one that fits.
You could use this method as a parameter wherever you would supply a delegate parameter with the same signature.

The parameter for .Select() is Func<T1, T2>() where T1 is the input parameter (the individual values of temps), and T2 is the return type.
Typically, this is written as a lambda function: x => return x + 1, etc. However, any method that fits the generic definitions can be used without having to be written as a lambda since the method name is the same as assigning the lambda to a variable.
So Func<string, int> parseInt = s => Convert.ToInt32(s); is syntactically equivalent to calling the method int.Parse(s).
The language creates the shortcut of automatically passing the Func parameter to the inside method to create more readable code.

Select LINQ IEnumerable<> extension method signature looks like that:
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector
)
Look at the selector argument. In your case you pass to Select .Net standard function int.Parse which has signature:
public static int Parse(
string s
)
.Net compiler can convert delegates to Func<...> or Action<...>. In case of int.Parse it can be converted to Func and therefore can be passed as argument to Select method.
Exactly the same with OrderBy. Look at its signature too.

Related

C# Linq and lambda

How does Select(int.Parse) work in such Linq expression?
"1,2,3,4,5".Split(',').Select(int.Parse).ToList(); //ok
"1,2,3,4,5".Split(',').Select(x => int.Parse(x)).ToList(); //ok
Why example with Console.Writeline returns compilation error?
"1,2,3,4,5".Split(',').Select(Console.WriteLine).ToList(); //error
"1,2,3,4,5".Split(',').Select(x => Console.WriteLine(x)).ToList(); //ok
When it is allowed to omit lambda like (x => ....(x))
Console.WriteLine as well as int.Parse are so-called method groups. Groups of methods. Because of the various overloads of those methods. It can be exactly one method, or multiple methods.
A method group can be converted to a delegate if the compiler can infer which method of the group is meant. For example the method group int.Parse can be a delegate to int.Parse(string) if a Func<string, int>is expected.
This works in your first example. Select expects a Func<T, T2> and your T is already set to be of type string. However, it does not work with your second example. Because while Console.WriteLine is a method group, not a single method in this group corresponds to the required Func<T, T2> because the return type of all of the methods in the group is void.
The signature of Select looks somewhat like this:
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector);
So for the selector a method (or lambda) with the signature
TResult Method(string s);
is expected. Console.WriteLine() is of return type void which is not a valid type for TResult. So in fact both lines:
"1,2,3,4,5".Split(',').Select(Console.WriteLine).ToList();
"1,2,3,4,5".Split(',').Select(x => Console.WriteLine(x)).ToList();
don't compile. Are you sure you really compiled that second line? My compiler raises error CS0411 for both lines.
Select is a projections statement, it transforms your object into a new object that you specify inside the Select.You need to loop and execute the WriteLine:
"1,2,3,4,5".Split(',').ToList().ForEach(x=> { Console.WriteLine(x); });
Select expects a parameter Func<char, T>, Console.WriteLine doesn't match that.
Almost all LINQ extensions accept a function that returns a value. Console.WriteLine does not return anything, so it can't be used as parameter.
"12345".Select(x => { Console.WriteLine(x); return x; }).ToList(); // this will work
"12345".Select(int.TryParse).ToList(); // this will NOT work because TryParse needs more than one parameter
"12345".ToList().ForEach(Console.WriteLine); // this will work because .ForEach accepts a method that does not return anything (void)
"12345".ToList().ForEach(int.Parse); // this will NOT work
It's allowed when the method signature is the same as LinQ expects.
In your first case, the Select's expected signature a method with one string parameter and return value of int (or simply Func<string, int>) and int.Parse method has the same signature, that's why it's working;
while in the second case, the Console.WriteLine's signature is a method with one string parameter and no return value (or return value of special type void) (or simply Action<string>), and hence signature that Select expects and signature that Console.WriteLine has do not match.

what is the use of ()=> in silverllight

Can you say what is the use of the ()=> and =>? I saw this in a code. I did not get any reference for this.
this.Dispatcher.BeginInvoke(()=>
{
//some thing..
};
=> is the lambda operator in C# and is read as "goes to". A lambda expression is an anonymous function and can be used to create a delegate.
Your example takes no arguments as indicated by the empty parens preceding the lambda operator. A lambda expression with one argument might look like this:
n => n.toString()
That expression would return the string representation of n, when invoked. A lambda expression can have multiple arguments as well, contained in parentheses:
(n, f) => n.toString(f)
A common use would be in a Func<T>:
Func<int, string> getString = n => n.toString();
int num = 7;
string numString = getString(num);
This is, of course, a silly example, but hopefully helps to illustrate its use.
This notation is that of a lambda expression which takes no argument. If the lambda expression made use of arguments they would be declared in the empty set of parenthesis as in say...
this.Dispatcher.BeginInvoke((x, y) => { do some' with x and/or y }, 12, somevar);
In a nutshell, lambda expressions allows creating "nameless" functions, right where they are needed.
In the example of the question, the BeginInvoke() method requires its first parameter to be a delegate (a "pointer to a method"), which is exactly what this lambda expression provides.
It's a lambda expression that has no parameters.
Check out this page http://codebetter.com/karlseguin/2008/11/27/back-to-basics-delegates-anonymous-methods-and-lambda-expressions/
If you don’t have any parameters, like in our example, you use empty
paranthesis:
() => {…}

Func vs. Action vs. Predicate [duplicate]

This question already has answers here:
Delegates: Predicate vs. Action vs. Func
(10 answers)
Closed 8 years ago.
With real examples and their use, can someone please help me understand:
When do we need a Func<T, ..> delegate?
When do we need an Action<T> delegate?
When do we need a Predicate<T> delegate?
The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).
Func is probably most commonly used in LINQ - for example in projections:
list.Select(x => x.SomeProperty)
or filtering:
list.Where(x => x.SomeValue == someOtherValue)
or key selection:
list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.
Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.
Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons (takes a generic parameter and returns bool).
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:
var result = someCollection.Select( x => new { x.Name, x.Address });
Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:
button1.Click += (sender, e) => { /* Do Some Work */ }
Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:
var filteredResults =
someCollection.Where(x => x.someCriteriaHolder == someCriteria);
I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

c# syntax and Linq, IQueryable

This is a question about the SYNTAX of c# and NOT about how we call/use IQueryable
Can someone please explain to me:
We have this declaration (System.Linq):
public static double Average<TSource>(this IQueryable<TSource> source,
Expression<Func<TSource, int>> selector)
and to call the Average
double average = fruits.AsQueryable().Average(s => s.Length);
I understand how to call the Average and all the similar static method of IQueryable
but I don’t understand the syntax of the declaration.
public static double Average<TSource>(this IQueryable<TSource> source,
Expression<Func<TSource, int>> selector)
What does the <TSource> mean in Average<TSource>(
and also the this IQueryable<TSource> source.
since only one parameter passes when we call it and the actual lambda expression (s => s.Length);
Thanks in advance.
The <TSource> part declares the generic type parameters of the method - basically what kind of element the sequence contains. You should definitely understand generics before you get too far into LINQ.
Then,
this IQueryable<TSource> source
indicates the first parameter of the method:
this indicates that it's an extension method
IQueryable<TSource> indicates the type of the parameter
source is the name of the parameter
The fact that it's an extension method is probably what's confusing you. When you call
query.Average(s => s.Length)
that is converted by the compiler into
Queryable.Average(query, s => s.Length)
You're declaring an extension method (that's the this keyword) that adds your method to any type implementing IQueryable<TSource> where TSource is the generic type, and remains the same throughout the expression.
The compiler can infer the generic type in this case, so you don't need to declare it when calling the method
TSource is the generic type that you will declare. It's basically what type the s is.
Average<TSource> because this is a Generic Method. The method can be run on a query or enumeration over any type (as long as a suitable selector for that type is provided).
this IQueryable<TSource> source because this is an Extension Method. Extension methods allow you to add additional methods to existing types without having to alter that type's definition. In this case Linq adds the Average method to the IQueryable interface without altering that interface.
<TSource> is a generic Parameter of the method.
this IQueryable<TSource> source denotes an extension method, this is syntactic sugar. In C#2.0, it would simply be a static method you'd have to call explicitly, with this, the compiler allows you to call it as if it was a member of the Type you are calling it on.
<X> is used to make generic functions that work with different types.
X add<X>(X a, X b){return a + b;}
int a = 1;
int b = 2;
int c = add<int>(a,b);
string d = "hello ";
string e = "world";
string f = add<string>(c,d);
this is a keyword for extensions methods:
string putinsidestars(this string x){
return "*" + x + "*";
}
string foo = "bar";
string z = foo.putinsidestars();
// z now contains *bar*

C# lambda - curry usecases

I read This article and i found it interesting.
To sum it up for those who don't want to read the entire post. The author implements a higher order function named Curry like this (refactored by me without his internal class):
public static Func<T1, Func<T2, TResult>>
Curry<T1, T2, TResult>(this Func<T1, T2, TResult> fn)
{
Func<Func<T1, T2, TResult>, Func<T1, Func<T2, TResult>>> curry =
f => x => y => f(x, y);
return curry(fn);
}
That gives us the ability to take an expression like F(x, y)
eg.
Func<int, int, int> add = (x, y) => x + y;
and call it in the F.Curry()(x)(y) manner;
This part i understood and i find it cool in a geeky way. What i fail to wrap my head around is the practical usecases for this approach. When and where this technique is necessary and what can be gained from it?
Thanks in advance.
Edited:
After the initial 3 responses i understand that the gain would be that in some cases when we create a new function from the curried some parameters are not re evalued.
I made this little test in C# (keep in mind that i'm only interested in the C# implementation and not the curry theory in general):
public static void Main(string[] args)
{
Func<Int, Int, string> concat = (a, b) => a.ToString() + b.ToString();
Func<Int, Func<Int, string>> concatCurry = concat.Curry();
Func<Int, string> curryConcatWith100 = (a) => concatCurry(100)(a);
Console.WriteLine(curryConcatWith100(509));
Console.WriteLine(curryConcatWith100(609));
}
public struct Int
{
public int Value {get; set;}
public override string ToString()
{
return Value.ToString();
}
public static implicit operator Int(int value)
{
return new Int { Value = value };
}
}
On the 2 consecutive calls to curryConcatWith100 the ToString() evaluation for the value 100 is called twice (once for each call) so i dont see any gain in evaluation here. Am i missing something ?
Currying is used to transform a function with x parameters to a function with y parameters, so it can be passed to another function that needs a function with y parameters.
For example, Enumerable.Select(this IEnumerable<T> source, Func<TSource, bool> selector) takes a function with 1 parameter. Math.Round(double, int) is a function that has 2 parameters.
You could use currying to "store" the Round function as data, and then pass that curried function to the Select like so
Func<double, int, double> roundFunc = (n, p) => Math.Round(n, p);
Func<double, double> roundToTwoPlaces = roundFunc.Curry()(2);
var roundedResults = numberList.Select(roundToTwoPlaces);
The problem here is that there's also anonymous delegates, which make currying redundant. In fact anonymous delegates are a form of currying.
Func<double, double> roundToTwoPlaces = n => Math.Round(n, 2);
var roundedResults = numberList.Select(roundToTwoPlaces);
Or even just
var roundedResults = numberList.Select(n => Math.Round(n, 2));
Currying was a way of solving a particular problem given the syntax of certain functional languages. With anonymous delegates and the lambda operator the syntax in .NET is alot simpler.
Its easier to first consider fn(x,y,z). This could by curried using fn(x,y) giving you a function that only takes one parameter, the z. Whatever needs to be done with x and y alone can be done and stored by a closure that the returned function holds on to.
Now you call the returned function several times with various values for z without having to recompute the part the required x and y.
Edit:
There are effectively two reasons to curry.
Parameter reduction
As Cameron says to convert a function that takes say 2 parameters into a function that only takes 1. The result of calling this curried function with a parameter is the same as calling the original with the 2 parameters.
With Lambdas present in C# this has limited value since these can provide this effect anyway. Although it you are use C# 2 then the Curry function in your question has much greater value.
Staging computation
The other reason to curry is as I stated earlier. To allow complex/expensive operations to be staged and re-used several times when the final parameter(s) are supplied to the curried function.
This type of currying isn't truely possible in C#, it really takes a functional language that can natively curry any of its functions to acheive.
Conclusion
Parameter reduction via the Curry you mention is useful in C# 2 but is considerably de-valued in C# 3 due to Lambdas.
In a sense, curring is a technique to
enable automatic partial application.
More formally, currying is a technique
to turn a function into a function
that accepts one and only one
argument.
In turn, when called, that function
returns another function that accepts
one and only one argument . . . and so
on until the 'original' function is
able to be executed.
from a thread in codingforums
I particularly like the explanation and length at which this is explained on this page.
One example: You have a function compare(criteria1, criteria2, option1, option2, left, right). But when you want to supply the function compare to some method with sorts a list, then compare() must only take two arguments, compare(left, right). With curry you then bind the criteria arguments as you need it for sorting this list, and then finally this highly configurable function presents to the sort algorithm as any other plain compare(left,right).
Detail: .NET delegates employ implicit currying. Each non-static member function of a class has an implicit this reference, still, when you write delegates, you do not need to manually use some currying to bind this to the function. Instead C# cares for the syntactic sugar, automatically binds this, and returns a function which only requires the arguments left.
In C++ boost::bind et al. are used for the same. And as always, in C++ everything is a little bit more explicit (for instance, if you want to pass a instance-member function as a callback, you need to explicitly bind this).
I have this silly example:
Uncurry version:
void print(string name, int age, DateTime dob)
{
Console.Out.WriteLine(name);
Console.Out.WriteLine(age);
Console.Out.WriteLine(dob.ToShortDateString());
Console.Out.WriteLine();
}
Curry Function:
public Func<string, Func<int, Action<DateTime>>> curry(Action<string, int, DateTime> f)
{
return (name) => (age) => (dob) => f(name, age, dob);
}
Usage:
var curriedPrint = curry(print);
curriedPrint("Jaider")(29)(new DateTime(1983, 05, 10)); // Console Displays the values
Have fun!
here's another example of how you might use a Curry function. Depending on some condition (e.g. day of week) you could decide what archive policy to apply before updating a file.
void ArchiveAndUpdate(string[] files)
{
Func<string, bool> archiveCurry1 = (file) =>
Archive1(file, "archiveDir", 30, 20000000, new[] { ".tmp", ".log" });
Func<string, bool> archiveCurry2 = (file) =>
Archive2("netoworkServer", "admin", "nimda", new FileInfo(file));
Func<string, bool> archvieCurry3 = (file) => true;
// backup locally before updating
UpdateFiles(files, archiveCurry1);
// OR backup to network before updating
UpdateFiles(files, archiveCurry2);
// OR do nothing before updating
UpdateFiles(files, archvieCurry3);
}
void UpdateFiles(string[] files, Func<string, bool> archiveCurry)
{
foreach (var file in files)
{
if (archiveCurry(file))
{
// update file //
}
}
}
bool Archive1(string fileName, string archiveDir,
int maxAgeInDays, long maxSize, string[] excludedTypes)
{
// backup to local disk
return true;
}
bool Archive2(string sereverName, string username,
string password, FileInfo fileToArchvie)
{
// backup to network
return true;
}

Categories

Resources