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).
Related
I just have a question about the Func and Action delegate.
I just wonder why you can't do this directly:
public static int addTowNumber(int a, int b)
{
return a + b;
}
Func<int, int, int> add = addTowNumber(1,2);
But you have to do this:
Func<int, int, int> add = addTowNumber;
var addNumber = add(1, 2);
Console.WriteLine(addNumber);
By passing the arguments you are actually invoking the method, and returning an int.
To store a reference to a function, to be invoked later, you don't pass the arguments, which is why this is correct:
Func<int, int, int> add = addTowNumber;
You can then provide any arguments you like when invoking:
int result1 = add(1, 2);
int result2 = add(3, 4);
If you want to defer execution of a method with predefined arguments, which is what it appears you are trying to do, you need to create a closure like this:
Func<int> add = () => addTowNumber(1, 2);
int result = add();
I have a Func in my code that's declared like this:
Func<string, int, bool> Filter { get; set; }
How can I reach the string and the int variables that are parameters of the Func in order to use them in my code?
The parameters only exist when the function is called... and they're only available within the function. So for example:
foo.Filter = (text, length) => text.Length > length;
bool longer = foo.Filter("yes this is long", 5);
Here, the value "yes this is long" is the value of the text parameter while the delegate is executing and likewise the value 5 is the value of the length parameter while it's executing. At other times, it's a meaningless concept.
What are you really trying to achieve? If you could give us more context, we could almost certainly help you better.
You could use an anonymous method:
Filter = (string s, int i) => {
// use s and i here and return a boolean
};
or a standard method:
public bool Foo(string s, int i)
{
// use s and i here and return a boolean
}
and then you could assign the Filter property to this method:
Filter = Foo;
See this sample here - http://www.dotnetperls.com/func
using System;
class Program
{
static void Main()
{
//
// Create a Func instance that has one parameter and one return value.
// ... Parameter is an integer, result value is a string.
//
Func<int, string> func1 = (x) => string.Format("string = {0}", x);
//
// Func instance with two parameters and one result.
// ... Receives bool and int, returns string.
//
Func<bool, int, string> func2 = (b, x) =>
string.Format("string = {0} and {1}", b, x);
//
// Func instance that has no parameters and one result value.
//
Func<double> func3 = () => Math.PI / 2;
//
// Call the Invoke instance method on the anonymous functions.
//
Console.WriteLine(func1.Invoke(5));
Console.WriteLine(func2.Invoke(true, 10));
Console.WriteLine(func3.Invoke());
}
}
I have seen someone write below kind of Func<> pattern. And I am trying to experiment with Funcs and Lambdas to get the concepts right.
so ExperimentalSelect returns a Func (with 2 args and bool return value).
But I fail to understand that how all of the 3 return statements are valid (1 at a time).
public static Func<BinaryTreeNode<int>, int, bool> nodeSelector = (x, y) =>
{
return x.Value > y;
};
public static Func<int, int, bool> intSelector = (x, y) =>
{
return x > y;
};
public static Func<BinaryTreeNode<int>, int, bool> ExperimentalSelect (int number)
{
return nodeSelector; // seems straightforward, i agree this should work
// how does this work ? intSelector is different type Func<>
// and it is executing it here, thereby returning the bool type result
// and not Func<> type as the return type of this method should
return (x, y) => intSelector(number, number);
// and how does this work ? what is node here ?
// and SomeMethod returns bool and not Func<> type
return (node, x) => SomeMethod(node, number, true);
}
private static bool SomeMethod(BinaryTreeNode<int> node, int someNumber,
bool doSomething)
{
return node.Value < someNumber;
}
EDIT:
If an ext. method expects a func
IEnumerable<int> selected = tree.TakeWhile(ExperimentalSelect);
How does SomeMethod work here ?, it is not a Func<> !
What does this syntax mean: (node, x) => SomeMethod(node, number, true);
Where is the node or x in picture here ?
Your comments above the returns are not correct.
intSelector and SomeMethod are not executed there. They will only be executed, when the return value of ExperimentalSelect is executed.
return (x, y) => intSelector(number, number);
This defines an anonymous method with two parameters. One of type BinaryTreeNode<int> and one of type int and a return value of bool, because that's what's the return type of ExperimentalSelect. The body of this anonymous method is the call to intSelector which is executed only, when the anonymous method itself is executed. This means, the body of this anonymous method can be anything you wish. It can even be multiple statements:
return (x, y) => {
var temp;
temp = y;
y = x;
x = temp;
return intSelector(number, y);
}
The anonymous method then is returned and not the result of executing it.
Your return statement is equivalent to the following:
Func<BinaryTreeNode<int>, int, bool> result =
(x, y) => intSelector(number, number);
return result;
You can verify this yourself with your debugger. Add a break point inside intSelector and step over the return statement. You will see, the breakpoint will not be hit.
One important point is the following:
Func can be seen as a pointer to a function.
Func<BinaryTreeNode<int>, int, bool> result =
(x, y) => SomeMethod(x, number, true);
This will create an anonymous method and result will point to that anonymous method.
However, have a look at the following code:
Func<BinaryTreeNode<int>, int, bool, bool> result = SomeMethod;
In this case, result will directly point to SomeMethod. No anonymous method is created here. Note the difference in the type of result. Because the first code only executes SomeMethod in the body of the anonymous method, the type of result doesn't need to match the signature of SomeMethod. But in the second code, you directly assign SomeMethod to result and thus the type of result must match the signature of SomeMethod.
More:
Look at the following code:
public static Func<BinaryTreeNode<int>, int, bool> ExperimentalSelect (int number)
{
return (x, y) => intSelector(number, number);
}
Func<BinaryTreeNode<int>, int, bool> result = ExperimentalSelect(10);
Console.WriteLine(result(30, 20)); // writes false
It will print false, although 30 is bigger than 20. Why?
The reason is, that your anonymous method has x and y as input parameters, but they are not used anywhere in its body. Instead, you pass number as both parameters to intSelector. The value of number is 10, and 10 isn't greater than 10.
The correct way to write this code would be like this:
public static Func<BinaryTreeNode<int>, int, bool> ExperimentalSelect ()
{
return (x, y) => intSelector(x, y);
}
Func<BinaryTreeNode<int>, int, bool> result = ExperimentalSelect();
Console.WriteLine(result(30, 20)); // writes true
As you can see, I now pass x and y to intSelector. I also removed the parameter number from ExperimentalSelect, because it is not used anywhere.
Ask yourself - are these two lines of code also correct:
Func<BinaryTreeNode<int>, int, bool> a =
(x, y) => intSelector(number, number);
Func<BinaryTreeNode<int>, int, bool> b =
(node, x) => SomeMethod(node, number, true);
The answer - yes. As it is for the return statements in your code.
I think perhaps you're either slightly misunderstanding the syntax or perhaps not understanding exactly what a Func is (apologies if either is not the case).
You seem to think that in this case
return (x, y) => intSelector(number, number);
what gets returned is the intSelector(number, number) part. But in reality the whole thing after return keyword is a return value. You can rewrite it like this:
return (BinaryTreeNode<int> x, int y) => intSelector(number,number);
which is roughly equivalent to returning an anonymous delegate with two parameters of type BinaryTreeNode<int> and int which returns the value of type bool. So it's your Func<BinaryTreeNode<int>, int, bool> right there.
Basically, the part to the left of => describes arguments and the part to the right is the method body, and the return type of the whole thing is the return type of the body.
Take a look at Lambda Expressions article by Eric White, it'll make sense to you.
In c# we can create delegates via a variety of means (e.g. Action<>, Func<>, delegate, lambdas, etc). But when you invoke those methods, you have to provide the parameter values for the delegate you are invoking:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5);
Is there a way in c# to encapsulate a method delegate WITH parameter values? Essentially delay invocation of a fully parametrized method? So you don't have to supply parameter values at invocation time?
For example something like this invalid code:
delegate int del(int i);
del myDelegate(5) = x => x * x;
int j = myDelegate;
I'm aware the use case isn't immediately obvious. In the case I'm currently looking at, I have a non-deterministic method that I would like the caller to be able to invoke without having to contain or be aware of the parameters the method needs. One way to achieve this would be via creating a class that encapsulates both the parameter values and the method delegate and have that referenced and invoked by the caller. But I'm just curious if there is an alternate, more succinct way.
This is called currying.
For example:
Action curried = () => myFunc(5);
Or,
Func<int, int, int> multiplier = (x, y) => x * y;
Func<int, int> doubler = x => multiplier(x, 2);
int eight = doubler(4);
Func<int, int> myDelegate = x => x * x;
Func<int> myDelegate5 = () => myDelegate(5);
int j = myDelegate5();
You could always wrap one delegate in another. As SLaks mentioned, this is called currying:
Func<int, int> square = i => i * i;
Func<int> squareFive = () => square(5);
int j = squareFive();
This can be done reasonably nicely without lambdas, with the aid of some generic classes and helper functions. I used such an approach in some vb.net/vs2005 code. If the goal is to yield a MethodInvoker which calls a function with three arguments of types T, U, and V, then create a class ParamInvoker<T,U,V> which holds fields param1, param2, and param3 (as types T, U, and V), and Action (of type Action<T,U,V>) and has a method DoIt(void) which calls Action(param1, param2, param3). The generic classes and helper functions get repetitive, but the syntax is pretty nice. For example (vb syntax, from memory, and C# syntax, guessing):
TheMethodInvoker = MakeParamInvoker(AddressOf MyFunction, 5, "Hello")
or
TheMethodInvoker = MakeParamInvoker(MyFunction, 5, "Hello")
assuming MyFunction takes an Integer and a String.
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