F# provides a feature, where a function can return another function.
An example of function generating a function in F# is:
let powerFunctionGenarator baseNumber = (fun exponent -> baseNumber ** exponent);
let powerOfTwo = powerFunctionGenarator 2.0;
let powerOfThree = powerFunctionGenarator 3.0;
let power2 = powerOfTwo 10.0;
let power3 = powerOfThree 10.0;
printfn "%f" power2;
printfn "%f" power3;
The best way I could come up with to achieve the same in C# was this:
class Program
{
delegate double PowerOf2(double exponent);
delegate double PowerOf3(double exponent);
delegate double PowerOfN(double n, double exponent);
static void Main(string[] args)
{
PowerOfN powerOfN = (a, b) => { return Math.Pow(a,b) ; };
PowerOf2 powerOf2 = (a) => { return powerOfN(2, a); };
PowerOf3 powerOf3 = (a) => { return powerOfN(3, a); };
double result = powerOf2(10);
Console.WriteLine(result);
result = powerOf3(10);
Console.WriteLine(result);
}
}
Is there some other way (/better way) of doing this?
Sure, that’s straightforward in C#:
Easy peasy. And if you don’t like the manifest typing, most of those can be replaced with
var.