As input to another program I am using I need to input a delegate of the form:
Func<double, double, double>.
I want the function to be sent in to be
F(a,b)=a+b*c+d
where c
and d
are known constants known at runtime.
So what I need is some method which takes the values c and d, and then gives me a function F(a,b)
. What I think I need to do is to first create the method:
double der(double a, double b, double c, double d)
{
return a + b * c + d;
}
And from this method I have to do something with delegates in order to get my function. Do you see how to solve this problem?
In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.
A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
You need to define the return value as your expected Func:
Func<double, double, double> MakeFunction(double c, double d)
now you can use a lambda expression to construct the function that you desire:
return (a,b) => a + b * c + d;
Explanation:
the (a,b)
denote the input parameters for your function. As the designated return value in the method signature specifies that this will be 2 parameters of type double
. the part after the =>
denotes the calculation that will be performed.
Now you can use it in the following way:
var myFunc = MakeFunction(3, 4);
Console.WriteLine(myFunc(1, 2));
TEST Code:
double a = 1;
double b = 2;
double c = 3;
double d = 4;
var myFunc = MakeFunction(c, d);
Console.WriteLine("Func: " + myFunc(a, b));
Console.WriteLine("Direct test: "a + b * c + d);
OUTPUT:
Func: 11
Direct test: 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With