In this post we implement the technique of Composing Functions
The idea of composing functions is based on the concatenation of operations
Consider the next code:
We could create functions to perform this and our code would be the next:
This then would be improved with Composition, which automates this step
The idea of composing functions is based on the concatenation of operations
Consider the next code:
int var1 = 100;
int var2 = var1 * 1024;
int var3 = var2 + 2048;
We could create functions to perform this and our code would be the next:
int var1 = 100;
int var2 = CalcVar2(var1);
int var3 = CalcVar3(var2);
int CalcVar2(int a)
{
return a * 1024;
}
int CalcVar3(int b)
{
return b + 2048;
}
This then would be improved with Composition, which automates this step
public static Func<TSource, TEndResult> Compose<TSource, TIntermediateResult, TEndResult>(
this Func<TSource, TIntermediateResult> func1,
Func<TIntermediateResult, TEndResult> func2)
{
return sourceParam => func2(func1(sourceParam));
}
var autoCalcVar1 = extensions.Compose(CalcVar2, CalcVar3);
int result = autoCalcVar1(var1);
Console.WriteLine(result);