6.5.2 function combinations in C #
The combination of functions in C # is possible, but the use is very limited, which is partly due to the fact that the scatter application in C # is not easy to use, but more importantly, because most operations are written by members rather than functions. But we can at least demonstrate the same idea in C #, listing 6.18 shows the implementation of the Compose method and the example used.
Listing 6.18 Implementing and using the Compose method (C #)
Static Func<a, c> Compose<a, b,c> (this func<a, b> F, Func<b, c> g) {
return (x) = g (f (x)); [1]
}
Using function composition in C # |
func<double, double> square = (n) = n * N; | [2]
Func<double, string> formatnum = (n) = n.tostring ("E"); |
var data = new Double[] {1.1, 2.2, 3.3};
var sqrs =data. Select (Square.compose (formatnum)); [3]
Prints: "1.210000E+000"; " 4.840000E+000 "; "1.089000E+001"
foreach (var s in Sqrs) Console.Write (s);
The function combination is implemented as the Func <t, r> delegate extension method, so we can use the dot notation to call on the function value, passing only one parameter value; in F #, this is written as a function with three parameters, although typically only two parameter values are used; in C #, We must implement it as a method with two parameter values, explicitly returning a Func delegate. We build the lambda function, have a parameter value, call the function that will be combined [1], and return the function as a delegate.
To test this method, we created two functions that we wanted to combine [2], and when we used a Select to manipulate the numbers in the collection, we used the combined function. Instead of explicitly specifying a lambda function as the parameter value, we call Compose to create the combined function value and pass it to the Select method [3].
In the last few sections, we already know that many useful processing functions are generics, some of which have even three type parameters. In F #, it is easy to write such a function because we do not have to explicitly write out the type because type inference has automatically inferred the type. So it's time to get a closer look at how this mechanism works.
6.5.2 function combinations in C #