Functional Programming using C# 4.0 – Functional Composition
C# 4.0 treats functions as regular objects which enables programmers to use functions as arguments of other functions. Functions those take other functions as arguments are technically called as higher order functions. Functional composition is one such example of higher order functions. Functional composition is a functional programming concept in which two or more functions can be combined to compose a higher order function.
Definition
Functional composition is a feature supported as part of functional programming features in C# 4.0. Suppose, say we have two functions represented by generic types: FuncCode Snippet
Code snippet for functional composition (for example described above):
static Func
{
return (x) => f2(f1(x));
}Application
The generic function shown in the code snippet above can be used in various scenarios. Following is an example:
Func
Func
Func
(2 * x + 3) * (2 * x + 3)
double y = gf(3); // result would be 81
Here is an example of reverse; i.e.
Func
2 * x * x + 3
double y2 = fg(3); // result would be 21
Two transforms g(f(x) )and f(g(x)) are different!