Create a function which gives us another function
Asked Answered
K

1

5

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?

Keratinize answered 27/2, 2019 at 12:59 Comment(1)
Be careful that Func<double,double,double> does not describe a function that takes 3 double as parameters, but rather a function that takes 2 double and returns a doubleSwen
D
7

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

Dutchman answered 27/2, 2019 at 13:10 Comment(2)
Thank you very much, I have to learn how to use lambda expressions.Keratinize
@Keratinize you're welcome. have fun, it is a very interesting topicDutchman

© 2022 - 2024 — McMap. All rights reserved.