I have been on that link but there are some lines I really don't understand.
1) List<()>
private readonly List<(string MemberName, Func<T, object> Fingerprint)> _fingerprints;
2) For < Tproperty>
public FingerprintBuilder<T> For<TProperty>(Expression<Func<T, TProperty>> memberExpression, Expression<Func<TProperty, TProperty>> fingerprint
How are they called? Can you provide some good links/explanations about them?
When you see
Func<T, TProperty> that is a delegate fingerprint, last item under <> is output, all others inputs.
So
Func<string, string, int> Fcn
Is a function that accepts 2 string parameters and returns integer value.
Lets define a function that accepts 2 strings and returns sum of their lengths
Func<string, string, int> Fcn = (string s1, string s2) => s1.Length + s2.Length;
var result = Fcn.Invoke("test", "test2");
Console.WriteLine(result); // will return 9
In your case, it is just some generic types, but functionally it is the same like this example
Related
Why can I invoke Parse method without parentheses since that method has 4 overloads?
For example in this case:
string[] aTemp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(aTemp, int.Parse);
The signature for ConvertAll is actually this:
public static TOutput[] ConvertAll<TInput, TOutput>(
TInput[] array,
Converter<TInput, TOutput> converter
)
Which the compiler can infer to be:
public static int[] ConvertAll<string, int>(
string[] array,
Converter<string, int> converter
)
From the signature for Int32.Parse:
public static int Parse(
string s
)
If you wanted to write out in long hand:
Converter<string, int> converter = new Converter<string, int>(Int32.Parse);
string[] aTemp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll<string, int>(aTemp, converter);
Note: Converter<TInput, TOutput> is actually a delegate that takes as input a parameter of type TInput and returns a value of type TOutput.
Array.ConvertAll takes two parameters, an array of TInput, and a converter delegate from TInput to TOutput. There's only one overload of int.Parse that matches the signature of a converter delegate -
public static int Parse(
string s
)
Putting together all of the information available, we can pick the right method to call.
I want to create an extension method which I can invoke on an object .
The return value will be defined by a function.
Something like this : ( this is just an example )
bool isMature= thePerson.Age.Apply<bool>(d => { if (d >18) return true;
return false;
})
and here is the extension method :
public static Tout Apply<Tout>(this Object obj, Func< Tout> f)
{
return f( );
}
The error : incompatible anonymous function signature
What am I doing wrong ?
Your method takes just a Func<Tout> - which is a function taking no parameters, but returning a value.
Your lambda expression has a parameter (d) - and it looks like you're assuming that's an integer. It's not clear what you're trying to do, but if you want to use a parameter in the lambda expression, you're going to have to change the signature from Func<TResult> to Func<TArg, TResult> or something similar - and provide an argument in the invocation.
If looks like you're expecting the input to the delegate instance to be the property value, so you would need to change the definition of the extension method to take this argument:
public static TOut ToFunc<TProperty, TOut>(this TProperty obj, Func<TProperty, TOut> f)
{
return f(obj);
}
// Usage
bool isMature = thePerson.Age.ToFunc<int, bool>(d => d > 18);
It seems a strange approach whatever the problem is.
This is a pointless excercise, devdigital has answered your question but what use is the answer.
So I can write the code,
var greaterThan18 = 20.ToFunc(n => n > 18);
but, why didn't I write
var greaterThan18 = 20 > 18;
all that is gained is a layer of indirection.
I've managed to do something like:
public static Tout ToFunc<T,Tout>(this T obj, Func<T, Tout> f)
{
return f(obj);
}
And the invocation is
var isMature = theperson.Age.ToFunc<int, bool>(i => i > 18);
However , I hated specifying <int, bool> every time
But thanks to resharper - which reminded me - I can invoke it like :
var isMature = theperson.Age.ToFunc(i => i > 18);
it is a nice util though , for small things. ( although it would be better to have a bool property which will indicate isMature....but ....you know , its nice.)
I think it would greatly simplify function overloading if I could just write the case that takes the most parameters and then simply stuff each case having less parameters with dummy params. For example..
// Add two integers
Func<int, int, int> addInts = (x, y) => { return x + y; };
// Add one to an integer
Func<int, int> addOne = (x) => { return x++; };
// In this case Func takes 2 args and has 1 return
public int IntCalc(Func<int,int,int> operation, int param1, int param2)
{
return operation(param1, param2);
}
// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
// This cast would allow me to do the overload
Func<int, int, int> castedOperation = (Func<int, int, int>)addOne;
return IntCalc(castedOperation, param1, 0);
}
So is there a way to do this? Is this a horrible practice?
You can only cast if the parameter signatures are compatible. In your case you'd need to define a lamda since converting a function with one parameter to a function with two parameters makes no sense in general.
Func<int, int, int> castedOperation = (i1,i2)=>addOne(i1);
If it's good practice depends on the contract of how the delegate will be used. If your functions with less parameters can fulfill that contract then this lamda based conversion is perfectly fine.
As a sidenode your addOne function is really ugly. While the increment of x has no effect because the parameter gets copied and thus only the copy is incremented and discared, implementing it as return x+1; would be much nicer than return x++; since you don't actually want to modify x.
Apart from the accepted answer you should also change the addOne to operation. So complete function would be
// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
// This cast would allow me to do the overload
Func<int, int, int> castedOperation = (i1,i2)=>operation(i1);
return IntCalc(castedOperation, param1, 0);
}
If your all parameters are the same type you can use params
adder(bool sample, params int[] a)
{
....
}
adder(2,3,4);
also you can use Named Parameter in C# 4.0.
Your approach is useful in constructors (you can do this with them).
i am reading Accelerated C# i don't really understand the following code:
public static Func<TArg1, TResult> Bind2nd<TArg1, TArg2, TResult> (
this Func<TArg1, TArg2, TResult> func,
TArg2 constant )
{
return (x) => func( x, constant );
}
in the last line what is x referring to? and there's another:
public static Func<TArg2, Func<TArg1, TResult>> Bind2nd<TArg1, TArg2, TResult>
( this Func<TArg1, TArg2, TResult> func )
{
return (y) => (x) => func( x, y );
}
How do i evaluate this? (y) => (x) => func( x, y ) what is passed where ... it does confusing.
Let's first simplify the code:
Func<int, int> B(Func<int, int, int> f, int c)
{
return x=>f(x, c);
}
This is just the same as:
class Locals
{
public int c;
public Func<int, int, int> f;
public int Magic(int x) { return f(x, c); }
}
Func<int, int> B(Func<int, int, int> f, int c)
{
Locals locals = new Locals();
locals.f = f;
locals.c = c;
return locals.Magic;
}
Now is it clear what x refers to? x is the parameter to function "Magic".
Now you can use B like this:
Func<int, int, int> adder = (a, b)=>a+b;
Func<int, int> addTen = B(adder, 10);
int thirty = addTen(20);
Make sense? See what is happening here? We're taking a function of two parameters and "fixing" one of the parameters to a constant. So it becomes a function of one parameter.
The second example takes that one step further. Again, simplify to get rid of the cruft so that you can understand it more easily:
Func<int, Func<int, int>> B2(Func<int, int, int> f)
{
return y=>x=>f(x,y);
}
This is the same as
class Locals3
{
public int y;
public int Magic3(int x)
{
return x + this.y;
}
}
class Locals2
{
public Func<int, int, int> f;
public Func<int, int> Magic2(int y)
{
Locals3 locals = new Locals3;
locals.y = y;
return locals.Magic3;
}
}
Func<int, Func<int, int>> B2(Func<int, int, int> f)
{
Locals2 locals = new Locals2();
locals.f = f;
return locals.Magic2;
}
So you say
Func<int, int, int> adder = (a, b)=>a+b;
Func<int, Func<int, int>> makeFixedAdder = B2(adder);
Func<int, int> add10 = makeFixedAdder(10);
int thirty = add10(20);
B is a parameter fixer. B2 makes a parameter fixer for you.
However, that's not the point of B2. The point of B2 is that:
adder(20, 10);
gives the same result as
B2(adder)(20)(10)
B2 turns one function of two parameters into two functions of one parameter each.
Make sense?
x is the parameter of the lambda, it is of type TArg1.
It can be helpful to pronounce the => as "maps to" as in "x maps to a new function with a constant of type TArg2 substituted into the original function delegate, func."
The variable x is an unbound variable. That represents an argument to the returned function from calling Bind2nd.
A few hours with Scheme would help you here, but try this.
When you call Bind2nd the returned result is a function. That function is defined as
(x) => func (x, constant)
Now that you have the above assigned to a variable, lets say lambda, you can call that function via the lambda variable
lambda(x);
The x defined in Bind2nd is just a variable that represents an argument to the function that will be returned to you.
A lambda expression is shorthand for anonymous method. Like anonymous method, lambda expression is assigned to delegate types. All conditions that apply for anonymous methods also apply to lambda expressions.
=> is called lambda operator, which is read as “goes to”. The left side of the operator specifies the input parameters separated by comma, and the right side specifies an expression or statement block which is called lambda body. (p1, p2, p3, …pN) => expression If you have only one parameter then you can skip the parenthesis p1 => expression;
I have written a small blog explaining lambda expression here Lambda Expression
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;
}